【问题标题】:Phalcon MVC Model called twice returns empty shared objects两次调用的 Phalcon MVC 模型返回空的共享对象
【发布时间】:2014-04-25 21:34:54
【问题描述】:

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

  • 库 - LibraryBase.php
  • 库 - User.php
  • 模型 - ModelBase.php
  • 模型 - UserGroupsModel.php
  • 控制器 - 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();
   }

}

用户.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(库)处理用户身份验证等。UsersController.php 处理用户。 LibraryBase 扩展 ModelBase 以访问公共对象。

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

如果不扩展ModelBase 并在UserGroupsModel() 中使用$this-&gt;db=$this-&gt;getDI()-&gt;getShared("db"); 手动分配对象,那么它可以工作。但是你需要在每个模型中分配公共对象。我可能错过了什么。

编辑:
我已经更新了代码,如果你运行这个例子,现在它会显示错误。

提前谢谢你。

【问题讨论】:

  • 你的测试代码是什么?你到底得到了哪个错误?
  • Linbow,我已经更新了测试代码。它显示的错误是(致命错误:在 C:\.... 中的非对象上调用成员函数 query())请告诉我您的想法。
  • 依赖注入类中设置的方法原型为public Phalcon\DI\ServiceInterface set (string $name, mixed $definition, [boolean $shared])。我在 Phalcon 的文档示例中读到,他们将可选参数 $shared 置于 true 中。如果你试试这个:$di-&gt;set('db', function() use ($config){ /*..*/ }, true);
  • 我不认为它会解决问题。我会在本地测试你的代码。
  • Lindblow,问题依然存在。

标签: php class phalcon


【解决方案1】:

在您的类 ModelBase 中,添加您放入的方法 onConstruct()

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

initialize 方法中删除上面的行。

根据 Phalcon 的文档:

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

不过,我不确定是否了解两者之间的区别。至少,它现在可以工作了 ;)

【讨论】:

  • 林布洛,谢谢!它很奇怪。我也不明白何时使用 intialize() 以及何时使用 onConstruct()。谢谢!
猜你喜欢
  • 2010-10-22
  • 2011-11-22
  • 1970-01-01
  • 2019-05-04
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多