du3669 2013-04-23 14:33
浏览 48
已采纳

Slim PHP:在课堂上提供$ app

I'm using controller/method as callbacks to application routes.

E.g.:

$app->get('/user/login', array('User', 'login'));

Here is the sample User class:

Class User {
  public function login() {
    print 'Login page.';
  }
}

How can I make the $app variable available automatically in all classes?
I know I can get it using getInstance() method, but I need to call it manually every time.

Thanks!

  • 写回答

2条回答 默认 最新

  • doulu1325 2013-04-23 14:35
    关注

    Create a base class that provides common elements and extend that base class in each of your controllers. Here is an example base class:

    class BaseController { 
       $app = new YourApp();
    
        function __construct() {
               $this->app->get('/user/login', array('User', 'login'));
    
    }
    

    Then, you can extend that class you your controller to get access to $app:

    class User extends BaseController {
    
        function yourFunction() {
            // $this->app is already set!
    }
    

    Update to parameterize the route:

    In BaseController:

    function __construct($route) {
           $this->app->get($route, array('User', 'login'));
    

    Then include the route parameter when you initialize your class:

    $user = new User('/user/login');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊