Slim研读笔记五之依赖注入容器(下)

来源:互联网 发布:java属性签名是什么 编辑:程序博客网 时间:2024/05/23 11:47

上节我们了解Pimple容器实现ArrayAccess接口的几个必须方法,这节让我们学习PimpleContainer的其他几个方法。 

    /**     * 标记可调用对象为工厂服务     * Marks a callable as being a factory service.     *     * @param callable $callable A service definition to be used as a factory     *     * @return callable The passed callable     *     * @throws ExpectedInvokableException Service definition has to be a closure or an invokable object     */    public function factory($callable)    {        if (!method_exists($callable, '__invoke')) {            throw new ExpectedInvokableException('Service definition is not a Closure or invokable object.');        }        // 前面已经了解factories属性是splstorage,可使用attach来绑定对象        $this->factories->attach($callable);        return $callable;    }
为何要调用对象为工厂服务呢?前面我们从offsetGet得知,在第一次加载服务时,会将闭包函数执行结果存储在$values[],将原生闭包存储在$rows[];第二次调用时,可直接返回$values[$id]存储的值。但如果我们希望服务每一次都是重新载入的呢?哈哈,聪明的你一定想到了,就是将调用factory函数啊。

“默认情况下,每次获得服务时,Pimple都会返回相同的实例 。如果要为所有调用返回不同的实例,请使用factory()方法包装匿名函数” 

   /**     * 禁止某服务不可被调用     * Protects a callable from being interpreted as a service.     *     * This is useful when you want to store a callable as a parameter.     *     * @param callable $callable A callable to protect from being evaluated     *     * @return callable The passed callable     *     * @throws ExpectedInvokableException Service definition has to be a closure or an invokable object     */    public function protect($callable)    {        if (!method_exists($callable, '__invoke')) {            throw new ExpectedInvokableException('Callable is not a Closure or invokable object.');        }        $this->protected->attach($callable);        return $callable;    }

今天内容略短,短是短,但也是一个知识点,哈哈。

原创粉丝点击