mercredi 31 janvier 2018

Interface with DB Facade in Laravel

First, I apologize if this is a stupid question. I recently read an article about repository design pattern and I have a problem when making interface implementation for Laravel Query Builder (Illuminate\Support\Facades\DB).

DatabaseService.php

use Modules\Core\Interfaces\IDatabase;
use \DB;

class DatabaseService implements IDatabase
{  
  protected $db;

  public function __construct(DB $db)
  {
    return $this->db = $db;
  }

  public function select($str)
  {
    $this->db::select($str);
    return $this->db;
  }

  public function table($tableName)
  {
    $this->db::table($tableName);
    return $this->db;
  }

  ...
}

IDatabase.php

<?php namespace Modules\Core\Interfaces;
interface IDatabase
{
  public function select($str);
  public function table($tableName);
  public function raw($rawQuery);
  public function transaction($callback);
  public function first();
  public function get();
}

CoreServiceProvider.php

...

public function register()
{
  ...
  $this->app->bind('Modules\Core\Interfaces\IDatabase', function($app) {
    $db = $app->make(DB::class);

    return new DatabaseService($db);
  });
  ...
}

And this is my query:

$badges = $this->db->table('mailbox as a')
          ->select($this->db->raw(
            "SUM(a.type = 'inbox') as inbox, 
             SUM(a.is_read = 0 AND a.type = 'inbox') as unread,
             SUM(a.type = 'sent') as sent,
             SUM(a.type = 'draft') as draft,
             SUM(a.type = 'outbox') as outbox,
             SUM(a.type = 'spam') as spam,
             SUM(a.type = 'trash') as trash,
             SUM(a.is_starred = 1) as starred"
          ))
          ->first();

With error message :

[2018-01-31 13:45:04] local.ERROR: Call to undefined method Illuminate\Support\Facades\DB::select() 
{"userId":1,"email":"info@narpandi.com","exception":"[object] 
(Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call 
to undefined method Illuminate\\Support\\Facades\\DB::select() at 
/var/www/personal-
website/app/Modules/Mailbox/Repositories/MailboxRepository.php:86)

How to do this correctly? Thank you for your kind help.

Aucun commentaire:

Enregistrer un commentaire