【问题标题】:Phalcon: global keyword doesn't work inside Index ControllerPhalcon:全局关键字在索引控制器中不起作用
【发布时间】:2014-04-09 11:19:37
【问题描述】:

这篇文章可能很长而且很乱,但是哦……所以我有我的原始 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();
}

【问题讨论】:

    标签: php global-variables phalcon


    【解决方案1】:

    哇,等一下……

    很高兴您发现自己编写的代码可以改进,但改进不仅仅意味着“将所有内容从一个地方转移到另一个地方”。

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

    假设您已成功设置 Phalcon,我建议您阅读 the first tutorial。这确实是一个很好的资源。

    MVC 架构是当今许多网站运行的东西,如果您不熟悉它,this link 可能会帮助您。

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

    在您的情况下,拥有这个 Smarty 类 as a service 听起来可能会很好,可以是 registered with Phalcon,然后可以是 dependency injected。

    试一试/阅读,让我/我们知道它对您的影响。

    【讨论】:

    • +1 我会加 2 便士。考虑使用 Phalcon 自动加载器和依赖注入器,这样你就不需要包含。就我个人而言,我认为 global 关键字是最后的手段,我只会在我有 3rd 方代码来哄骗工作时才使用它,我在我写的东西中不需要它。函数中的函数可能在其他语言中也可以工作,我听说有人声称他们在 PHP 中工作,但我认为它们比它们的价值更麻烦
    猜你喜欢
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多