ホームページ バックエンド開発 PHPチュートリアル 素晴らしい PHP 依存関係注入コンテナーのニキビ

素晴らしい PHP 依存関係注入コンテナーのニキビ

Jun 23, 2016 pm 01:58 PM
php pimple 頼る 注射

制御の反転とも呼ばれる依存関係の挿入は、コンピューター プログラムの結合問題を軽減するための重要なオブジェクト指向プログラミングの原則であり、コンポーネント間の直接の依存関係を排除し、コンポーネントの開発をより柔軟に使用できるようにします。 Javaフレームワークでは。 PHPは言語の特性上、Javaのセットを完全にコピーすることはできませんが、簡単な機能であれば実現可能です。 pimple は、PHP コミュニティで人気のある IOC コンテナです。

composer を使用して、require "pimple/pimple": "1.*" を追加できます

pimple の利点は、ファイルが 1 つだけでシンプルであることです

<?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 配列のハッシュテーブルの実装は簡単で、コンテナ自体のクエリ効率もそれほど低くありません。 zf1 の Zend_Register や Yii のプロキシ フォームと同様に、これは一般的によりシンプルで直感的です。

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ヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Ubuntu および Debian 用の PHP 8.4 インストールおよびアップグレード ガイド Ubuntu および Debian 用の PHP 8.4 インストールおよびアップグレード ガイド Dec 24, 2024 pm 04:42 PM

PHP 8.4 では、いくつかの新機能、セキュリティの改善、パフォーマンスの改善が行われ、かなりの量の機能の非推奨と削除が行われています。 このガイドでは、Ubuntu、Debian、またはその派生版に PHP 8.4 をインストールする方法、または PHP 8.4 にアップグレードする方法について説明します。

CakePHP データベースの操作 CakePHP データベースの操作 Sep 10, 2024 pm 05:25 PM

CakePHP でデータベースを操作するのは非常に簡単です。この章では、CRUD (作成、読み取り、更新、削除) 操作について理解します。

CakePHP の日付と時刻 CakePHP の日付と時刻 Sep 10, 2024 pm 05:27 PM

Cakephp4 で日付と時刻を操作するには、利用可能な FrozenTime クラスを利用します。

CakePHP ファイルのアップロード CakePHP ファイルのアップロード Sep 10, 2024 pm 05:27 PM

ファイルのアップロードを行うには、フォーム ヘルパーを使用します。ここではファイルアップロードの例を示します。

CakePHP ルーティング CakePHP ルーティング Sep 10, 2024 pm 05:25 PM

この章では、ルーティングに関連する次のトピックを学習します。

CakePHP について話し合う CakePHP について話し合う Sep 10, 2024 pm 05:28 PM

CakePHP は、PHP 用のオープンソース フレームワークです。これは、アプリケーションの開発、展開、保守をより簡単にすることを目的としています。 CakePHP は、強力かつ理解しやすい MVC のようなアーキテクチャに基づいています。モデル、ビュー、コントローラー

CakePHP バリデータの作成 CakePHP バリデータの作成 Sep 10, 2024 pm 05:26 PM

Validator は、コントローラーに次の 2 行を追加することで作成できます。

CakePHP のロギング CakePHP のロギング Sep 10, 2024 pm 05:26 PM

CakePHP へのログインは非常に簡単な作業です。使用する関数は 1 つだけです。 cronjob などのバックグラウンド プロセスのエラー、例外、ユーザー アクティビティ、ユーザーが実行したアクションをログに記録できます。 CakePHP でのデータのログ記録は簡単です。 log()関数が提供されています

See all articles