douliu1092 2016-08-30 04:00
浏览 73
已采纳

如何在Silex中的自定义类中使用$ app?

I know this looks like a dupllicate of Inject Silex $app in my custom class and others, but I couldn't get it working from their solutions.

I define my service like this:

$app['user.repo'] = function () {
    return new MyApp\Repository\User();
};

My class looks like this:

<?php
namespace MyApp\Repository;
use Silex\Application; 

class User {
    public function findAll(Application $app) {
        $users = $app['db']->fetchAll('SELECT * FROM user');
        return $users;
    }
}

And I use the service like this:

$users = $app['user.repo']->findAll($app);

How can I do this same thing without putting $app in all my methods?

  • 写回答

1条回答 默认 最新

  • donglu9825 2016-08-30 05:11
    关注

    Why don't you inject it?

    $app['user.repo'] = function () use ($app) {
        return new MyApp\Repository\User($app);
    };
    

    And here's your modified class:

    <?php
    
    namespace MyApp\Repository;
    use Silex\Application; 
    
    class User {
        /** @var Application */
        protected $app;
    
        public function __construct(Application $app) {
            $this->app = $app;
        }
    
        public function findAll() {
            $users = $app['db']->fetchAll('SELECT * FROM user');
    
            return $users;
        }
    }
    

    Or even better: instead of injecting the whole application (and thus hiding your real dependencies, making unit testing a pain), only inject what you really need:

    $app['user.repo'] = function () use ($app) {
        return new MyApp\Repository\User($app["db"]);
    };
    

    This way your class becomes:

    <?php
    
    namespace MyApp\Repository;
    use Silex\Application; 
    
    class User {
        protected $db;
    
        public function __construct($db) {
            $this->db = $db;
        }
    
        public function findAll() {
            $users = $this->db->fetchAll('SELECT * FROM user');
    
            return $users;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?