Phalcon MVC模型调用两次返回空共享对象

时间:2014-04-25 21:34:54

标签: php class phalcon

当我尝试两次声明Model时,第二个声明返回空的共享依赖项。我可能错过了一些东西。这就是我所拥有的。

  • 图书馆 - LibraryBase.php
  • 图书馆 - User.php
  • 型号 - ModelBase.php
  • 型号 - 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);
}

我们的想法是扩展ModelBase并访问公共依赖项。 Users.php(库)正在处理用户身份验证等UserController.php处理用户。 LibraryBase扩展了ModelBase以访问公共对象。

UserGroupsModel()的第一次调用是从User.php库完成的,它可以正常工作。对UserGroupsModel()的第二次调用是从UserController.php完成的,它在模型中返回空的$this->db对象。

如果没有延长ModelBase并使用$this->db=$this->getDI()->getShared("db");中的UserGroupsModel()手动分配对象,那么它可以正常工作。但是,您需要在每个模型中分配公共对象。我可能错过了一些东西。

编辑:
我已经更新了代码,现在如果您运行此示例则显示错误。

提前谢谢。

1 个答案:

答案 0 :(得分:3)

在您的班级ModelBase中,添加您放置的方法onConstruct()

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

initialize方法中删除上面的行。

根据Phalcon的文件:

  

initialize()方法仅在请求期间调用一次,它旨在执行适用于在应用程序中创建的模型的所有实例的初始化。如果要为创建的每个实例执行初始化任务,可以“onConstruct”。

我不确定两者之间的区别。至少,它现在有效;)