PHP的轻量级依赖管理库

v1.0.1 2016-06-21 05:21 UTC

This package is auto-updated.

Last update: 2024-08-29 03:55:20 UTC


README

Zit

Build Status Total Downloads Latest Stable Version

描述

Zit 是一个受 Pimple 启发的轻量级依赖注入库,由 Selvin Ortiz 编写

要求

安装

composer require selvinortiz/zit

测试

sh spec.sh

用法

依赖管理是一个难以解释的话题,但基本上,Zit 允许你将一些东西放入其中,然后在应用程序的任何地方将其弹出。

// Make an instance
$app = Zit::make();

// Stash a config object
$app->stash('config', new Config(['usr' => 'root', 'pwd' => 'secret']));

// Bind a session generator
$app->bind('session', function() {
    return new Session();
});

// Bind a database generator
$app->bind('db', function($app) {
    return new Db($app->config->usr, $app->config->pwd);
});

// Extend your $app with new functionality
$app->extend('end', function($app) {
    $app->db->close();
    $app->session->destroy();
});

// Finish
$app->end();

你也可以不创建新实例,而是以静态方式使用 Zit

// Stash a config object
Zit::stash('config', new Config(['usr' => 'root', 'pwd' => 'secret']));

// Bind a session generator
Zit::bind('session', function() {
    return new Session();
});

// Bind a database generator
Zit::bind('db', function($zit) {
    return new Db($zit->config->usr, $zit->config->pwd);
});

// Extend Zit with new functionality
Zit::extend('end', function($zit) {
    $zit->db->close();
    $zit->session->destroy();
});

// Finish
Zit::end();

你应该使用哪种方法?无论你更喜欢哪种。如果你不确定,你可以使用静态方式,除非你需要创建一个自己的实例来扩展 Zit

注意

无论你使用 bind()stash() 还是 extend(),你都可以使用以下方式将其弹出

Zit::pop('db');  // Formal
Zit::db();       // Via __callStatic()
Zit::db          // Via __callStatic() property sniffing

// If you had done $app = Zit::make()
$app->pop('db'); // Formal
$app->db();      // Via __call()
$app->db;        // Via __get()

API

pop($id, $args = array())

pop() 允许你从容器中弹出依赖项

Zit::pop('db');
// See the note above on popping stuff out

bind($id, callable $serviceGenerator)

bind() 允许你注册一个服务生成器。当你需要实例化一个依赖于配置对象的服务的例子时,这很有用。服务仅在首次调用时生成 一次

Zit::make()->bind('db', function($zit) {
   return new Db($zit->config->usr, $zit->config->pwd); 
});

stash($id, $service)

stash() 允许你在容器内存储任何东西。你得到你放进去的东西,这在你需要存储大量需要在整个应用程序中可访问的东西时很有用。

Zit::make()->stash('session', new Session())

extend($id, $callback)

extend() 使你能够向容器添加新功能

Zit::make()->extend('logout', function($zit) {
    $zit->session->logout();
});

贡献

Zit 希望对 首次贡献者 友好。只需按照以下步骤操作,如果在途中有任何问题,请随时联系。

  1. 创建分支
  2. 创建你的错误修复或功能分支
  3. 提交并推送你的更改
  4. 提交一个拉取请求

许可证

Zit 是开源软件,许可协议为 MIT 许可证