How to call Moldel in My Controller?


My Project:


   $container['db'] = function ($container) {
    return new App\Helpers\Database($container['settings']['db']);


namespace App\Controllers;

use Interop\Container\ContainerInterface;

class Controller
    protected $container;

    public function __construct(ContainerInterface $container)
        $this->container = $container;


    public function __get($property)
        if ($this->container->{$property}) {
            return $this->container->{$property};


namespace App\Controllers\Admin;    
use App\Models\User    
    Class HomeController extends Controller

       public function index($request, $response, $agr)
        // How to call Model here ? How do I have must to code Model ?
        //Exp:  $user = User::getUsername($agr['id']);


$this->get('', '\App\Controllers\Admin\HomeCtroller:index')->setName('home');

Final, my question at comment in HomeCtroller: How to call User Model or other Model enywhere ?


With the exception of things like a spelling error in your route (HomeController), missing a semicolon after you import your User model, missing class braces, etc, your example line looks plausible for the rest of your code.

Are you getting an error, and if so what does the error say?


Do you use Eloquent?
You can have a look at :


i’m Just use PDO.


namespace App\Models;
Abstract  class Model{

    protected $db;
    public function __construct($db)
        $this->db = $db;



namespace App\Models;
class User extends Model
    public  function attempt($file='')
        $this->db->query('SELECT email FROM '. $this->db->table('users'). ' WHERE email = :email');
        $this->db->bind(':email', $file);
        $email = $this->db->getOne();
        return $email;

at HomeCtroller.php

use App\Models\User;

$user =  new User($this->db);
$email = $user->attempt('');

But i want:

$email = User::attempt('');

So, i’ll to code Model Class, How ?


Why are you injection your DB connection into the model?
I suggest you to use the User Cconstructor for create new Users.
Use a UserRepository intead!

PdoUserRepository implments UserRepositoryInterface
       private $pdo;

       public function __construnct(\PDO $pdo)
             $this->pdo = $pdo;

        public function getUserByUsername(string $username) : User // Return a User Object and do not couple it to the database :)