dimanche 6 septembre 2020

Create helper class to add custom queries to database query builder?

I want to add global custom queries using the DB facade:

\DB::table('users')->myCustomQuery()->get();

I tried it by manipulating the DatabaseServiceProvider as explained in Add scope queries to database query builder? but I could not make it work.

Thus, I tried to create this helper class to add custom queries:

<?php

namespace App\Utilities;

use DB;

class CustomDB
{
    private $db;

    private static $instance = null;

    private $exitCalls;

    private function __construct()
    {
        $this->exitCalls = ['get', 'find', 'pluck', 'first', 'value', 'chunk', 'chunkById', 'count', 'max', 'avg', 'exists', 'doesntExist'];
    }

    public function __call($name, $arguments)
    {
        $result = call_user_func_array([self::$instance->db, $name], $arguments);

        if (in_array($name, $this->exitCalls)) {
            return $result;
        }

        return self::$instance;
    }

    public static function table($string)
    {
        if (self::$instance == null) {
            self::$instance = new CustomDB();
        }

        self::$instance->db = DB::table($string);

        return self::$instance;
    }

    public function myCustomQuery()
    {
         self::$instance->db->where('name','=','frank');
         return self::$instance;
    }
}

Now

CustomDB::table('users')->myCustumQuery()->get();

works!

But something like

CustomDB::table('users')->where(function($query){
    $query->myCustomQuery();
})->get();

Does not work. That is because where(...) is called on self::$instance->db (which is an instance of Ilumminate/Database/DatabaseManager and thus $query->myCustomQuery() is called on the DatabaseManager and not my helper class, thus he does not know the method myCustomQuery.

Any idea how to make this helper class work for recursive queries?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire