1

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.

5
  • What is your test code ? And which error did you get exactly ?
    – Linblow
    Apr 25, 2014 at 22:49
  • Linbow, I have updated the code for testing. The error it shows is (Fatal error: Call to a member function query() on a non-object in C:\....) Please let me know what you think.
    – cjrb
    Apr 26, 2014 at 0:01
  • The prototype of the method set in the Dependency Injection class is public Phalcon\DI\ServiceInterface set (string $name, mixed $definition, [boolean $shared]). I read in Phalcon's doc example that they put the optional argument $shared to true. What if you try this : $di->set('db', function() use ($config){ /*..*/ }, true); ?
    – Linblow
    Apr 26, 2014 at 15:59
  • I don't think it'll solve the problem. I'll test your code locally.
    – Linblow
    Apr 26, 2014 at 16:07
  • Lindblow, the problem still exist.
    – cjrb
    Apr 27, 2014 at 17:50

1 Answer 1

3

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 ;)

1
  • Linblow, thanks! It is strange. I also don't understand when to use intialize() and when onConstruct(). Thanks!
    – cjrb
    May 1, 2014 at 18:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.