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

awesome PHP之依赖注入器皿pimple

Jun 13, 2016 am 11:55 AM
callable object the this

awesome 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->protected = new \SplObjectStorage();        foreach ($values as $key => $value) {            $this->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->frozen[$id])) {            throw new \RuntimeException(sprintf('Cannot override frozen service "%s".', $id));        }        $this->values[$id] = $value;        $this->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->keys[$id])) {            throw new \InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));        }        if (            isset($this->raw[$id])            || !is_object($this->values[$id])            || isset($this->protected[$this->values[$id]])            || !method_exists($this->values[$id], '__invoke')        ) {            return $this->values[$id];        }        if (isset($this->factories[$this->values[$id]])) {            return $this->values[$id]($this);        }        $this->frozen[$id] = true;        $this->raw[$id] = $this->values[$id];        return $this->values[$id] = $this->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->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->keys[$id])) {            if (is_object($this->values[$id])) {                unset($this->factories[$this->values[$id]], $this->protected[$this->values[$id]]);            }            unset($this->values[$id], $this->frozen[$id], $this->raw[$id], $this->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->factories->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->protected->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->keys[$id])) {            throw new \InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));        }        if (isset($this->raw[$id])) {            return $this->raw[$id];        }        return $this->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->keys[$id])) {            throw new \InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));        }        if (!is_object($this->values[$id]) || !method_exists($this->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->values[$id];        $extended = function ($c) use ($callable, $factory) {            return $callable($factory($c), $c);        };        if (isset($this->factories[$factory])) {            $this->factories->detach($factory);            $this->factories->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->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->factory(function ($c) {    return new Session($c['session_storage']);});
로그인 후 복사


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

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

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

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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

2개월 만에 휴머노이드 로봇 '워커S' 옷 개기 가능 2개월 만에 휴머노이드 로봇 '워커S' 옷 개기 가능 Apr 03, 2024 am 08:01 AM

기계력 보고서 편집자: 우신(Wu Xin) 국내판 휴머노이드 로봇+대형 모델팀이 옷 접기 등 복잡하고 유연한 재료의 작업 작업을 처음으로 완료했습니다. OpenAI 멀티모달 대형 모델을 접목한 Figure01이 공개되면서 국내 동종업체들의 관련 진전이 주목받고 있다. 바로 어제, 중국의 "1위 휴머노이드 로봇 주식"인 UBTECH는 Baidu Wenxin의 대형 모델과 긴밀하게 통합되어 몇 가지 흥미로운 새로운 기능을 보여주는 휴머노이드 로봇 WalkerS의 첫 번째 데모를 출시했습니다. 이제 Baidu Wenxin의 대형 모델 역량을 활용한 WalkerS의 모습은 이렇습니다. Figure01과 마찬가지로 WalkerS는 움직이지 않고 책상 뒤에 서서 일련의 작업을 완료합니다. 인간의 명령을 따르고 옷을 접을 수 있습니다.

Java Object를 바이트로, 바이트를 Object로 변환하는 방법은 무엇입니까? Java Object를 바이트로, 바이트를 Object로 변환하는 방법은 무엇입니까? Apr 20, 2023 am 11:37 AM

Object에서 byte로, byte에서 Object로 오늘은 Object에서 byte로 변환하는 방법과 byte에서 Object로 변환하는 방법을 알아보겠습니다. 먼저 학생 클래스를 정의합니다. packagecom.byteToObject;importjava.io.Serialized;publicclassstudentimplementsSerialized{privateintsid;privateStringname;publicintgetSid(){returnsid;}publicvoidsetSid(in

Java 객체 클래스에서 메소드를 사용하는 방법 Java 객체 클래스에서 메소드를 사용하는 방법 Apr 18, 2023 pm 06:13 PM

1. Object 클래스 소개 Object는 Java에서 기본적으로 제공하는 클래스입니다. Object 클래스를 제외한 Java의 모든 클래스는 상속 관계를 갖습니다. 기본적으로 Object 상위 클래스를 상속합니다. 즉, Object의 참조를 이용하여 모든 클래스의 객체를 받을 수 있습니다. 예: Object를 사용하여 모든 클래스의 객체 수신 classPerson{}classStudent{}publicclassTest{publicstaticvoidmain(String[]args){function(newPerson());function(newStudent());}public

Java의 동기화 원리 및 사용 시나리오와 Callable 인터페이스의 사용 및 차이점 분석 Java의 동기화 원리 및 사용 시나리오와 Callable 인터페이스의 사용 및 차이점 분석 Apr 21, 2023 am 08:04 AM

1. 기본 기능 1. 낙관적 잠금으로 시작하여 잠금 충돌이 빈번하면 비관적 잠금으로 변환됩니다. 2. 경량 잠금 구현으로 시작하여 잠금이 오랫동안 유지되면 잠금이 해제됩니다. 3. 경량 잠금을 구현할 때 가장 많이 사용되는 스핀 잠금 전략 4. 불공정 잠금 5. 재진입 잠금 6. 읽기-쓰기 잠금이 아님 2. JVM 잠금 프로세스를 동기화합니다. 잠금은 잠금 없음, 편향된 잠금, 경량 잠금 및 중량 잠금 상태로 구분됩니다. 상황에 따라 순차적으로 업그레이드될 예정입니다. 편향된 자물쇠는 남자 주인공이 자물쇠이고 여자 주인공이 실이라고 가정합니다. 이 스레드만 이 자물쇠를 사용하면 남자 주인공과 여자 주인공은 결혼 증명서를 받지 못해도 영원히 행복하게 살 수 있습니다. -비용 운영) 그러나 여성 조연이 나타납니다.

Java는 객체 클래스의 getClass() 함수를 사용하여 객체의 런타임 클래스를 얻습니다. Java는 객체 클래스의 getClass() 함수를 사용하여 객체의 런타임 클래스를 얻습니다. Jul 24, 2023 am 11:37 AM

Java는 Object 클래스의 getClass() 함수를 사용하여 객체의 런타임 클래스를 얻습니다. Java에서 각 객체에는 객체의 속성과 메서드를 정의하는 클래스가 있습니다. getClass() 함수를 사용하여 객체의 런타임 클래스를 가져올 수 있습니다. getClass() 함수는 Object 클래스의 멤버 함수이므로 모든 Java 객체가 이 함수를 호출할 수 있습니다. 이 기사에서는 getClass() 함수를 사용하는 방법을 소개하고 몇 가지 코드 예제를 제공합니다. get을 사용하세요

이 점을 이해하고 프론트엔드 70%를 따라잡는 글 이 점을 이해하고 프론트엔드 70%를 따라잡는 글 Sep 06, 2022 pm 05:03 PM

Vue2의 이 포인팅 문제로 인해 동료가 버그로 인해 화살표 기능이 사용되어 해당 소품을 얻을 수 없게 되었습니다. 제가 그에게 소개했을 때 그는 그것을 몰랐고, 그래서 저는 일부러 프론트엔드 커뮤니케이션 그룹을 살펴보았습니다. 지금까지 적어도 70%의 프론트엔드 프로그래머들은 오늘 그것을 이해하지 못하고 있습니다. 모든 것이 불분명하다면 이 링크를 아직 배우지 않았다면 큰 소리로 말해주세요.

Vue2가 이를 통해 다양한 옵션의 속성에 접근할 수 있는 이유에 대해 이야기해보겠습니다. Vue2가 이를 통해 다양한 옵션의 속성에 접근할 수 있는 이유에 대해 이야기해보겠습니다. Dec 08, 2022 pm 08:22 PM

이 글은 Vue 소스 코드를 해석하는 데 도움이 될 것이며 이를 사용하여 Vue2의 다양한 옵션에서 속성에 액세스할 수 있는 이유를 소개하는 것이 모든 사람에게 도움이 되기를 바랍니다!

Java의 기본 데이터 유형과 객체 간의 관계는 무엇입니까 Java의 기본 데이터 유형과 객체 간의 관계는 무엇입니까 May 01, 2023 pm 04:04 PM

기본 데이터 유형과 Object 사이의 관계 Object가 모든 유형의 기본 클래스라는 것을 누구나 들어봤을 것입니다. 그러나 이 문장은 실제로 정확하지 않습니다. 왜냐하면 Java의 기본 데이터 유형은 Object와 관련이 없기 때문입니다. 예를 들어 swap 메소드를 호출할 때 실제로 Object는 기본 데이터 유형과 아무 관련이 없기 때문에 int 유형을 swap(Objectobj) 메소드에 직접 전달할 수 없습니다. 이제 자동으로 Wrapping하게 되어 Integer 타입이 되었고, 기본 데이터 타입의 래퍼 클래스인 Swap 메소드를 성공적으로 호출할 수 있게 되었습니다.

See all articles