简易 Ioc 容器

简易版控制反转Ioc

// Iocindex.php
<?php

/*
*   控制反转
*/

interface Log {
    public function info();
}

class DatabaseLog implements Log {
    public function info() {
        echo 'database log';
    }   
}

class FileLog implements Log {
    public function info() {
        echo 'file log';
    }
}

class User {
    protected $log;
    public function __construct(Log $log) {
        $this->log = $log;
    }
    public function writeLog() {
        $this->log->info();
    }
}


class Ioc {
    private $binds = [];

    public function bind($contract, $concrete) {
        $this->binds[$contract] = $concrete;
    }

    private function methodBindParams($className){
        $reflect = new Reflect($className,'__construct');
        return $reflect->bindParamsToMethod();
    }

    public function make($className){
        $methodBindParams = $this->methodBindParams($className);
        $reflect = new Reflect($className,'__construct');
        return $reflect->make($this->binds,$methodBindParams);
    }
}


class Reflect{
    private $className;

    private $methodName;

    public function __construct($className,$methodName){
        $this->className = $className;
        $this->methodName = $methodName;
    }

    //绑定参数到方法
    public function bindParamsToMethod(){

        $params = [];

        $method  = new ReflectionMethod($this->className,$this->methodName);

        foreach ($method->getParameters() as $param) {
            $params[] =  [$param->name,$param->getClass()->name];
        }

        return [$this->className=> $params];
    }

    public function make($bind,$methodBindParams){
        $args = [];
        foreach ($methodBindParams as $className => $params) {
            foreach ($params as $param) {
                list($paramName,$paramType) = $param;
                $paramName = new $bind[$paramType]();

                array_push($args, $paramName);
            }
        }
        $reflectionClass = new ReflectionClass($this->className);
        return $reflectionClass->newInstanceArgs($args);
    }
}
$ioc = new Ioc();
$ioc->bind('Log', 'FileLog');
$user = $ioc->make('User');

$user->writeLog();
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 1
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!