백엔드 개발 PHP 튜토리얼 awesome PHP之依赖注入容器pimple

awesome PHP之依赖注入容器pimple

Jun 23, 2016 pm 01:58 PM
php pimple 의존하다 주입

依赖注入(Dependency Injection)又叫控制反转(Inversion of Control)是一个重要的面向对象编程的法则来削减计算机程序的耦合问题,它能消除组件间的直接依赖关系,让组件的开发更独立,使用更灵活,在java框架中应用非常广泛。在php中由于语言特性不能完全照搬java的那一套,但简单的功能还是可以实现的。pimple就是php社区中比较流行的一种ioc容器。

可以用composer添加 require  "pimple/pimple": "1.*"

pimple的优势是简单,就一个文件

<?php /* * This file is part of Pimple. * * Copyright (c) 2009 Fabien Potencier * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished * to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *//** * Pimple main class. * * @package pimple * @author  Fabien Potencier */class Pimple implements \ArrayAccess{    private $values = array();    private $factories;    private $protected;    private $frozen = array();    private $raw = array();    private $keys = array();    /**     * Instantiate the container.     *     * Objects and parameters can be passed as argument to the constructor.     *     * @param array $values The parameters or objects.     */    public function __construct(array $values = array())    {        $this->factories = new \SplObjectStorage();        $this-&gt;protected = new \SplObjectStorage();        foreach ($values as $key =&gt; $value) {            $this-&gt;offsetSet($key, $value);        }    }    /**     * Sets a parameter or an object.     *     * Objects must be defined as Closures.     *     * Allowing any PHP callable leads to difficult to debug problems     * as function names (strings) are callable (creating a function with     * the same name as an existing parameter would break your container).     *     * @param  string           $id    The unique identifier for the parameter or object     * @param  mixed            $value The value of the parameter or a closure to define an object     * @throws RuntimeException Prevent override of a frozen service     */    public function offsetSet($id, $value)    {        if (isset($this-&gt;frozen[$id])) {            throw new \RuntimeException(sprintf('Cannot override frozen service "%s".', $id));        }        $this-&gt;values[$id] = $value;        $this-&gt;keys[$id] = true;    }    /**     * Gets a parameter or an object.     *     * @param string $id The unique identifier for the parameter or object     *     * @return mixed The value of the parameter or an object     *     * @throws InvalidArgumentException if the identifier is not defined     */    public function offsetGet($id)    {        if (!isset($this-&gt;keys[$id])) {            throw new \InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));        }        if (            isset($this-&gt;raw[$id])            || !is_object($this-&gt;values[$id])            || isset($this-&gt;protected[$this-&gt;values[$id]])            || !method_exists($this-&gt;values[$id], '__invoke')        ) {            return $this-&gt;values[$id];        }        if (isset($this-&gt;factories[$this-&gt;values[$id]])) {            return $this-&gt;values[$id]($this);        }        $this-&gt;frozen[$id] = true;        $this-&gt;raw[$id] = $this-&gt;values[$id];        return $this-&gt;values[$id] = $this-&gt;values[$id]($this);    }    /**     * Checks if a parameter or an object is set.     *     * @param string $id The unique identifier for the parameter or object     *     * @return Boolean     */    public function offsetExists($id)    {        return isset($this-&gt;keys[$id]);    }    /**     * Unsets a parameter or an object.     *     * @param string $id The unique identifier for the parameter or object     */    public function offsetUnset($id)    {        if (isset($this-&gt;keys[$id])) {            if (is_object($this-&gt;values[$id])) {                unset($this-&gt;factories[$this-&gt;values[$id]], $this-&gt;protected[$this-&gt;values[$id]]);            }            unset($this-&gt;values[$id], $this-&gt;frozen[$id], $this-&gt;raw[$id], $this-&gt;keys[$id]);        }    }    /**     * 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 InvalidArgumentException Service definition has to be a closure of an invokable object     */    public function factory($callable)    {        if (!is_object($callable) || !method_exists($callable, '__invoke')) {            throw new \InvalidArgumentException('Service definition is not a Closure or invokable object.');        }        $this-&gt;factories-&gt;attach($callable);        return $callable;    }    /**     * 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 InvalidArgumentException Service definition has to be a closure of an invokable object     */    public function protect($callable)    {        if (!is_object($callable) || !method_exists($callable, '__invoke')) {            throw new \InvalidArgumentException('Callable is not a Closure or invokable object.');        }        $this-&gt;protected-&gt;attach($callable);        return $callable;    }    /**     * Gets a parameter or the closure defining an object.     *     * @param string $id The unique identifier for the parameter or object     *     * @return mixed The value of the parameter or the closure defining an object     *     * @throws InvalidArgumentException if the identifier is not defined     */    public function raw($id)    {        if (!isset($this-&gt;keys[$id])) {            throw new \InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));        }        if (isset($this-&gt;raw[$id])) {            return $this-&gt;raw[$id];        }        return $this-&gt;values[$id];    }    /**     * Extends an object definition.     *     * Useful when you want to extend an existing object definition,     * without necessarily loading that object.     *     * @param string   $id       The unique identifier for the object     * @param callable $callable A service definition to extend the original     *     * @return callable The wrapped callable     *     * @throws InvalidArgumentException if the identifier is not defined or not a service definition     */    public function extend($id, $callable)    {        if (!isset($this-&gt;keys[$id])) {            throw new \InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));        }        if (!is_object($this-&gt;values[$id]) || !method_exists($this-&gt;values[$id], '__invoke')) {            throw new \InvalidArgumentException(sprintf('Identifier "%s" does not contain an object definition.', $id));        }        if (!is_object($callable) || !method_exists($callable, '__invoke')) {            throw new \InvalidArgumentException('Extension service definition is not a Closure or invokable object.');        }        $factory = $this-&gt;values[$id];        $extended = function ($c) use ($callable, $factory) {            return $callable($factory($c), $c);        };        if (isset($this-&gt;factories[$factory])) {            $this-&gt;factories-&gt;detach($factory);            $this-&gt;factories-&gt;attach($extended);        }        return $this[$id] = $extended;    }    /**     * Returns all defined value names.     *     * @return array An array of value names     */    public function keys()    {        return array_keys($this-&gt;values);    }}
로그인 후 복사

pimple类就继承一个php数组对象接口,在程序整个生命周期中,各种属性、方法、对象、闭包都可以注册其中,得易于php的数组的hashtable实现,容器本身的查询效率不算是太低。类似zf1中的Zend_Register或者Yii的委托代理形式,总体来说还是pimple直观些。

pimple只是实现了一个容器的概念,关于依赖注入自动创建关联对象的功能可以参照Laravel4和z2中的实现。一个例子代码:

require __DIR__ . '/vendor/autoload.php';  // define some services$container['session_storage'] = function ($c) {    return new $c['session_storage_class']($c['cookie_name']);};$container['session'] = function ($c) {    return new Session($c['session_storage']);};// get the session object$session = $container['session'];$container['session'] = $container-&gt;factory(function ($c) {    return new Session($c['session_storage']);});
로그인 후 복사


본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

뜨거운 기사 태그

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Dec 24, 2024 pm 04:42 PM

Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드

CakePHP 날짜 및 시간 CakePHP 날짜 및 시간 Sep 10, 2024 pm 05:27 PM

CakePHP 날짜 및 시간

CakePHP 파일 업로드 CakePHP 파일 업로드 Sep 10, 2024 pm 05:27 PM

CakePHP 파일 업로드

CakePHP 프로젝트 구성 CakePHP 프로젝트 구성 Sep 10, 2024 pm 05:25 PM

CakePHP 프로젝트 구성

CakePHP 라우팅 CakePHP 라우팅 Sep 10, 2024 pm 05:25 PM

CakePHP 라우팅

CakePHP 토론 CakePHP 토론 Sep 10, 2024 pm 05:28 PM

CakePHP 토론

CakePHP 빠른 가이드 CakePHP 빠른 가이드 Sep 10, 2024 pm 05:27 PM

CakePHP 빠른 가이드

PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 Dec 20, 2024 am 11:31 AM

PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법

See all articles