Container服务容器:
为了更好的提现原理, 这个实现是对laravel的结构做了简化
Contract-契约的存在
用来约束不同的DB服务类的实现, 就好像一个程序模板.
配套facade
一个快速从容器中调用类方法的方式
下面开始创建项目
$ cd /vagrant/b
$ composer init
Package name (<vendor>/<name>) [vagrant/b]: masterzcw/tiny-laravel
Description []: This is a small project modeled fater laravel.
Author [, n to skip]: 275107947 <275107947@qq.com>
Minimum Stability []:
Package Type (e.g. library, project, metapackage, composer-plugin) []: library
License []: MIT
Define your dependencies.
Would you like to define your dependencies (require) interactively [yes]? n
Would you like to define your dev dependencies (require-dev) interactively [yes]? n
{
"name": "kevin/tiny-laravel",
"description": "This is a small project modeled fater laravel.",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "275107947",
"email": "275107947@qq.com"
}
],
"require": {}
}
Do you confirm generation [yes]? yes
此时在插件根目录创建出文件composer.json文件, 内容如上面的json.
载入命名空间
vendor/kevin/tiny-laravel
---
...
"autoload":{
"psr-4":{
"Kevin\\TinyLaravel\\":"./src/"
}
},
"require": {}
---
更新composer
$ composer update
此时,在如下文件中会出现这个命名空间的注册, 证明composer.json的配置是ok的
/vendor/composer/autoload_psr4.php
index.php
require __DIR__.'/vendor/autoload.php';
use Masterzcw\TinyLaravel\Application\Application;
use Masterzcw\TinyLaravel\Facades\DB;
// 注册服务, 使用容器的单例
$providers = [
// \Masterzcw\TinyLaravel\Contracts\Databases\IDB::class => \Masterzcw\TinyLaravel\Databases\Oracle\DB::class,
\Masterzcw\TinyLaravel\Contracts\Databases\IDB::class => \Masterzcw\TinyLaravel\Databases\MySQL\DB::class,
];
foreach($providers as $key => $val){
Application::getInstace()->bind($key, $val);
}
// 直接通过容器调用
$db = Application::getInstace()->make(\Masterzcw\TinyLaravel\Contracts\Databases\IDB::class);
echo $db->introduce()."<br>";
// 通过门面类调用指定的服务, 因为门面封装了容器的Application::getInstace()->make($class);
echo DB::introduce()."<br>";
以上是基本描述具体参见github上的代码
github:
https://github.com/masterzcw/componentized-tiny-laravel