Phalcon:全局关键字dos';不能在索引控制器内工作


Phalcon: global keyword doesn't work inside Index Controller

这篇文章可能很长很乱,但哦。。。所以我有我的网站在原始PHP

我的原始文件结构:

/Index.php
/Users.php
/Smarty.class.php
/db.php
/Stats.php
/css/
/js/

现在我想将每个索引文件"移植"到phalcon控制器中,如下所示:

/Controllers/IndexController.php
/Controllers/UsersController.php
/Smarty.class.php
/db.php
/css/
/js/

问题是全局关键字在IndexController.php中不起作用:

class IndexController extends 'Phalcon'Mvc'Controller
{
          include "/db.php"; // $db is initialized there
          include_once ("Smarty.class.php"); 
          $main_smarty = new Smarty;
   public function indexAction()
  {
     function doSearch($limit) {
    global $db, $current_user, $main_smarty; // db and smarty objects
            $db->get_results("// my query"");
    $search_clause = $this->get_search_clause();
            $main_smarty->assign('search', $this->searchTerm);
    }
   }
  }

致命错误:在非对象上调用成员函数get_results()

但它在我的原始代码中运行良好,没有Phalcon。

            include "/db.php";
        function doSearch($limit) {
    global $db, $current_user, $main_smarty;
    $search_clause = $this->get_search_clause();
            $main_smarty->assign('search', $this->searchTerm);

我的引导程序(Index.php)文件:

try {
//Register an autoloader
$loader = new 'Phalcon'Loader();
$loader->registerDirs(array(
    'Controllers/',
))->register();
// DI
$di = new Phalcon'DI'FactoryDefault();
//     View component
$di->set('view', function(){
    $view = new 'Phalcon'Mvc'View();
    $view->setViewsDir('/');
    return $view;
});
$application = new 'Phalcon'Mvc'Application($di);
echo $application->handle()->getContent();
} catch('Phalcon'Exception $e) {
 echo "PhalconException: ", $e->getMessage();
}

哇,等一下。。

你已经确定了你写的代码可以改进,这很好,但改进不仅仅意味着"把所有东西从一个地方移到另一个地方"。

你有机会做的是重新思考你是如何做事的,并进入一种"更有条理"(在我看来……)的工作方式。

假设你已经成功地安装了Phalcon,我建议你通读第一个教程。这确实是一个很好的资源。

MVC体系结构是当今许多网站运行的东西,如果你不熟悉它,这个链接可能会帮助你。

很难直接回答你的问题,因为我想读一读后,一切都会变得更清楚。

在您的情况下,将这个Smarty类作为一个服务可能会很好,它可以向Phalcon注册,然后可以注入依赖项。

试试看,让我/我们知道你的情况。