2

我似乎无法让 Slim 框架访问 PHP 类范围内的函数:

<?php

class Controller {
    private $app;

    public function __construct() {
        $this->app = new Slim();

        $this->app->get('/', $this->home);

        $this->app->run();
    }

    public function home() {
        echo 'hi';
    }
}

这会导致以下错误:

致命错误:在 /Users/Oliver/Dropbox/Sites/grapevine/application/controller.php:9 中带有消息“未定义属性:Controller::$home”的未捕获异常“ErrorException” 堆栈跟踪:#0 /Users/Oliver/Dropbox /Sites/grapevine/application/controller.php(9): Slim::handleErrors(8, 'Undefined prope...', '/Users/Oliver/D...', 9, Array) #1 /Users/ Oliver/Dropbox/Sites/grapevine/public/index.php(14): Controller->__construct() #2 {main} 在第 9 行的 /Users/Oliver/Dropbox/Sites/grapevine/application/controller.php 中抛出

我试过这样做:

$this->app->get('/', $this->home());

但随后路由被忽略,每个页面都显示'hi',而不仅仅是'/'。

4

3 回答 3

12

使用成员函数的回调语法:

$this->app->get('/', array($this, 'home'));
于 2012-02-25T15:22:03.957 回答
2

以下应该可以工作(不过,可能需要将您的主页功能更改为静态!):

$this->app->get('/', "Controller::home");
于 2012-02-25T15:13:21.020 回答
1

我有这个从 Slim 内部容器注入构造函数的解决方案

基本上主要的魔法隐藏在__call功能中

class App extends Slim
 public function __call($name, $params) {
  return function () use ($name, $params) {
  list($class, $action) = explode('_', $name . '_handle'); // default method is handle

  $args = [];
  $class = new \ReflectionClass($class);
  $constructor = $class->getConstructor();
  foreach ($constructor->getParameters() as $param) {
   $args[] = ($param->name === 'app') ? $this : $this->container->get($param->name);
  }
  $controller = $class->newInstanceArgs($args);
  return call_user_func([$controller, $action], func_get_args() + $params);
  };
 }
}

控制器需要在构造函数参数中有 App:

class Homepage {

 public $app;

 public function __construct(\App $app) {
  $this->app = $app;
 }
}

而 index.php 只有路由器设置

$app = new \App();
$app->get('/', $app->Homepage());
$app->run(

在此处查看完整代码https://gist.github.com/OzzyCzech/7230064

于 2013-10-30T10:15:12.407 回答