PHP code example of giginc / cakephp3-driver-csv

1. Go to this page and download the library: Download giginc/cakephp3-driver-csv library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

giginc / cakephp3-driver-csv example snippets


 'Datasources' => [
...

    'csv' => [
        'className' => 'Giginc\Csv\Database\Connection',
        'driver' => 'Giginc\Csv\Database\Driver\Csv',
        'baseDir' => './', // local path on the server relative to CONFIG
    ],
],

//src/Model/Table/ProductsTable.php
namespace App\Model\Table;

use Giginc\Csv\ORM\Table;

class ProductsTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setPrimaryKey('id');
        $this->setSchemaRow(1);      // Schema row is 1 row.
        $this->setDelimiter(',');    // default ,
        $this->setEnclosure('"');    // default "
        $this->setEscape("\\");      // default \\
        $this->setTable('products'); // load file is CONFIG/materials.csv
    }

    /**
     * Returns the database connection name to use by default.
     *
     * @return string
     */
    public static function defaultConnectionName()
    {
        return 'csv';
    }

    /**
     * findOk
     *
     * @param \League\Csv\Statement $query Query.
     * @param array $options Option.
     * @access public
     * @return \Cake\ORM\Query
     */
    public function findOk($query, array $options)
    {
        $query = $query
            ->where(function(array $row) {
                return $row['status'] == 'ok';
            });

        return $query;
    }
}

namespace App\Controller;

use App\Controller\AppController;

/**
 * Pages Controller
 *
 * @property \App\Model\Table\PagesTable $Pages
 *
 * @method \App\Model\Entity\Review[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
 */
class PagesController extends AppController
{
    /**
     * Index method
     *
     * @access public
     * @return \Cake\Http\Response|void
     */
    public function index()
    {
        $this->loadModel('Products');
        $data = $this->Products->find();
    }

    /**
     * View method
     *
     * @param mixed $id
     * @access public
     * @return \Cake\Http\Response|void
     */
    public function view($id)
    {
        $this->loadModel('Products');
        $data = $this->Products->get(1);
    }

}