Question

When I try to declare a Model twice, the second declaration returns empty shared dependencies. I'm probably missing something. Here what I have.

  • Library - LibraryBase.php
  • Library - User.php
  • Model - ModelBase.php
  • Model - UserGroupsModel.php
  • Controller - UsersController.php

ModelBase.php

namespace Models;

class ModelBase extends \Phalcon\Mvc\Model{

   public $db; // Setting up db connection

   // Initialize model
   function initialize()
   {
      $this->db=$this->getDI()->getShared("db"); // Setting up db connection from injector
   }

}

UserGroupsModel.php

namespace Models;

class UserGroupsModel extends ModelBase{

   function initialize()
   {
      parent::initialize();   
   }

   function test()
   {
      $result=$this->db->query('SELECT * FROM user_groups');
      if($result->numRows()>0)
      {
         $data=$result->fetchAll();
         var_dump($data);
      }
   }

}

LibraryBase.php

namespace Libraries;

class LibraryBase extends \Models\ModelBase {

   function initialize()
   {
      parent::initialize();
   }

}

User.php

namespace Libraries;

class User extends LibraryBase {
    function initialize()
    {
       parent::initialize();
    }

    function get_group()
    {
      $UserGroupsModel=new \Models\UserGroupsModel();
      $UserGroupsModel->test();
    }

    function access()
    {
       $this->get_group();
    }
}

UsersController.php

namespace Controllers;

class UsersController extends \Phalcon\Mvc\Controller{

   function initialize()
   {
      $this->user->access(); // Checking user access
   }

   function UserGroupsAction() // User group action
   {
       $UserGroupsModel=new \Models\UserGroupsModel();
       $UserGroupsModel->test();
   }
}

index.php

// Bootstrap 
try {

    //Register an autoloader
    $loader = new \Phalcon\Loader();

    $loader->registerNamespaces([
         'Controllers' =>'app/controllers/',
         'Models' =>'app/models/',
         'Libraries'=>'app/libraries/'
    ])->register();

    //Create a DI
    $di = new Phalcon\DI\FactoryDefault();

    // Setting User Class
    $di->set("user", function (){       
       $user=new \Libraries\User(); // Initiates class
       return $user;       
    });

    //Setup the database service
    $di->set('db', function() use ($config){
        return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
            "host" => "localhost",
            "username" => "root",
            "password" => "123456",
            "dbname" => "database",
            'options' => [PDO::ATTR_PERSISTENT => FALSE,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC],
         ));
    });

    //Setup the view component
    $di->set('view', function(){
        $view = new \Phalcon\Mvc\View();
        // PHP files for as view files
        $view->registerEngines(array(
            ".php" => "Phalcon\Mvc\View\Engine\Php"
         ));
        $view->setViewsDir('app/views/'); // Setting a desktop version path first. If mobile device is used, redirect to mobile directory
        return $view;
    });

    // Setup Router
    $di->set('router', function(){

         $router = new \Phalcon\Mvc\Router(false);

         $router->removeExtraSlashes(true);
         $router->setDefaultNamespace("Controllers");
         $router->setDefaultAction("index");
         $router->notFound(array("controller"=>"errors","action"=>"e404","namespace"=>"Controllers"));

         // Add root controller
         $router->add('/:controller/:action', array(
            'namespace' => 'Controllers',
            'controller' => 1,
            'action'=>2 
         ));         

         return $router;
    });

    //Handle the request
    $application = new \Phalcon\Mvc\Application($di);

    echo $application->handle()->getContent();

} catch(\Phalcon\Exception $e) {

      echo "PhalconException: ", $e->getMessage();
      echo "<br>";
      var_dump($e);
}

The idea is to extend ModelBase and to have access to common dependencies. Users.php (library) is processing user authentication etc. UsersController.php dealing with users. LibraryBase extends ModelBase to access common objects.

First call for UserGroupsModel() is done from User.php library and it works. The second call for UserGroupsModel() is done from UserController.php and it returns empty $this->db object in the model.

If not extending ModelBase and manually assign objects using $this->db=$this->getDI()->getShared("db"); in the UserGroupsModel() then it works. But then you need to assign common objects in every Model. I'm probably missing something.

EDIT:
I have updated the codes, now it shows error if you are running this example.

Thank you in advance.

Was it helpful?

Solution

In your class ModelBase, add the method onConstruct() in which you put:

$this->db = $this->getDI()->getShared("db");

Remove the line above from the initialize method.

According to Phalcon's documentation:

The initialize() method is only called once during the request, it’s intended to perform initializations that apply for all instances of the model created within the application. If you want to perform initialization tasks for every instance created you can ‘onConstruct’.

I'm not sure to understand the difference between the both though. At least, it now works ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top