Code Monkey home page Code Monkey logo

datatables's Introduction

Datatables library for PHP

Latest Stable Version PHP Composer license

Simplify your Datatables server-side processing effortlessly using our lightning-fast PHP library, streamlining your workflow seamlessly. Live Demo

Features

Installation

NOTE: version 2.0+ requires php 7.1.3+ (php supported versions)

The recommended way to install the library is with Composer

If you haven't started using composer, I highly recommend you to use it.

Put a file named composer.json at the root of your project, containing this information:

{
    "require": {
       "ozdemir/datatables": "2.*"
    }
}

And then run:

composer install

Or just run :

composer require ozdemir/datatables

Add the autoloader to your project:

    <?php

    require_once 'vendor/autoload.php';

You're now ready to begin using the Datatables php library.

    <?php
    require_once 'vendor/autoload.php';

    use Ozdemir\Datatables\Datatables;
    use Ozdemir\Datatables\DB\MySQL;

    $config = [ 'host'     => 'localhost',
                'port'     => '3306',
                'username' => 'homestead',
                'password' => 'secret',
                'database' => 'sakila' ];

    $dt = new Datatables( new MySQL($config) );

    $dt->query('Select film_id, title, description from film');

    echo $dt->generate();

If you are using a php framework such as codeigniter or laravel, you can use the relevant database adapter.

// Codeigniter 4 Example

<?php

namespace App\Controllers;

use Config\Database;
use Ozdemir\Datatables\Datatables;
use Ozdemir\Datatables\DB\Codeigniter4Adapter;

class Home extends BaseController
{
    public function index()
    {
        return view('index');
    }

    public function ajax()
    {
        // CI 4 builder class
        $db = Database::connect();

        $builder = $db->table('Track');
        $builder->select('TrackId, Name, UnitPrice');

        // Datatables Php Library
        $datatables = new Datatables(new Codeigniter4Adapter);

        // using CI4 Builder
        $datatables->query($builder);

        // alternatively plain sql
        // $datatables->query('Select TrackId, Name, UnitPrice from Track');

        return $this->response->setJSON($datatables->generate()->toJson());
    }
}
// Laravel Example

<?php
// routes/web.php 

use Ozdemir\Datatables\Datatables;
use Ozdemir\Datatables\DB\LaravelAdapter;

Route::get('/ajax/laravel', function () {

    $dt = new Datatables(new LaravelAdapter);

    $dt->query(
      Track::query()
          ->select([
              'TrackId',
              'Track.Name',
              'Title as Album',
              'MediaType.Name as MediaType',
              'UnitPrice',
              'Milliseconds',
              'Bytes',
          ])
          ->join('Album', 'Album.AlbumId', 'Track.AlbumId')
          ->join('MediaType', 'MediaType.MediaTypeId', 'Track.MediaTypeId')
    ); // same as the previous example, sql statement can be used.

    return $dt->generate();
});

Methods

This is the list of available public methods.

query($query) required

  • sets the sql query

generate() required

  • runs the queries and build outputs
  • returns the output as json
  • same as generate()->toJson()

toJson()

  • returns the output as json
  • should be called after generate()

toArray()

  • returns the output as array
  • should be called after generate()

add($column, function( $row ){})

  • adds extra columns for custom usage

edit($column, function($row){})

  • allows column editing

filter($column, function(){})

  • allows custom filtering
  • it has the methods below
    • escape($value)
    • searchValue()
    • defaultFilter()
    • between($low, $high)
    • whereIn($array)
    • greaterThan($value)
    • lessThan($value)

hide($columns)

  • removes the column from output
  • It is useful when you only need to use the data in add() or edit() methods.

setDistinctResponseFrom($column)

  • executes the query with the given column name and adds the returned data to the output with the distinctData key.

setDistinctResponse($output)

  • adds the given data to the output with the distinctData key.

getColumns()

  • returns column names (for dev purpose)

getQuery()

  • returns the sql query string that is created by the library (for dev purpose)

Example

    <?php
    require_once 'vendor/autoload.php';

    use Ozdemir\Datatables\Datatables;
    use Ozdemir\Datatables\DB\SQLite;

    $path = __DIR__ . '/../path/to/database.db';
    $dt = new Datatables( new SQLite($path) );

    $dt->query('Select id, name, email, age, address, plevel from users');

    $dt->edit('id', function($data){
        // return a link.
        return "<a href='user.php?id=" . $data['id'] . "'>edit</a>";
    });

    $dt->edit('email', function($data){
        // masks email : [email protected] => m***@mail.com
        return preg_replace('/(?<=.).(?=.*@)/u','*', $data['email']);
    });

    $dt->edit('address', function($data){
        // checks user access.
        $current_user_plevel = 4;
        if ($current_user_plevel > 2 && $current_user_plevel > $data['plevel']) {
            return $data['address'];
        }

        return 'you are not authorized to view this column';
    });
    
    $dt->hide('plevel'); // hides 'plevel' column from the output

    $dt->add('action', function($data){
        // returns a link in a new column
        return "<a href='user.php?id=" . $data['id'] . "'>edit</a>";
    });

    $dt->filter('age', function (){
        // applies custom filtering.
        return $this->between(15, 30);
    });

    echo $dt->generate()->toJson(); // same as 'echo $dt->generate()';

Road Map

  • better test suites for each class
  • improve integrations for php frameworks

Requirements

Composer
DataTables > 1.10
PHP > 7.1.3

License

Copyright (c) 2015 Yusuf ÖZDEMİR, released under the MIT license

If you like the library

Buy Me A Coffee

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.