简易 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 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 1
(= ̄ω ̄=)··· 暂无内容!

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