phpcodeignitermethodsquery-builderclass-extensions

How to create a custom_where() method by extending CodeIgniter's query builder


How can I properly make my own implementation of a query builder method in CodeIgniter.

$this-db
    ->from('myTable')
    ->where('id', 1)
    ->custom_where('name', 'customsValues')
    ->get()

There values are irrelevent here. I've already built a class that extends en current CI_DB_query_builder, but I have no idea where to set my class to be used as the primary query builder.


Solution

  • I've found the answer to my question. However, any other good answer is welcome since mine is not the prettiest.

    First let me walk you through what I was trying to do.
    I wanted to use Tightenco's collect library to use collection rather than array. This way I could use more intuitive chain array function:
    $this->db->from('...')->results()->map(function($items) { ... })->toArray();

    Then, i wanted to have my own function, such as where_if.

    I started by making my own query builder class that extended from CI_DB_query_builder. I have an example below:

    <?php
    require BASEPATH . 'database/DB_query_builder.php';
    
    
    class CustomQueryBuilder extends CI_DB_query_builder {
        public function where_if($where, $value, $condition) : CustomQueryBuilder {
            if($condition) {
                $this->where($where, $value);
            }
            return $this;
        }
    
        public function results() : \Tightenco\Collect\Support\Collection {
            return \Tightenco\Collect\Support\Collection::make($this->get()->result_array());
        }
    }
    

    To link this class as the main Querybuilder, I had to change it in the file system/database/DB.php.
    I changed the path of the require_once in line 171 :

    require_once(APPPATH.'libraries/QueryBuilder/CustomQueryBuilder.php');
    

    I also changed the alias class on line 182

    class CI_DB extends CustomQueryBuilder { }
    

    Please note that this is on codeigniter v3.0.6, your line number may differ.

    Now, i needed to import some function so the autocomplete on PHPStorm would still point to my custom querybuilder, because once i used the function from, it returned a CI_DB_query_builder object.
    Here is how I imported the function I used the most.

    /**
     * Nothing changed here, for autocompletion only
     * @param mixed $from
     * @return $this|CI_DB_query_builder
     */
    public function from($from) {
        parent::from($from);
        return $this;
    }
    

    I really hope this helps people that are trying the same thing. If you got any feedback on this project, please let me know !