1. 依赖注入案例:
Model模型代码:
实例
namespace Model;
class Model{
public function getData(){
return [
['name'=>'张志伟','sex'=>'男','age'=>22,'marriage'=>'未婚','wages'=>8000,'occupation'=>'外卖骑手'],
];
}
}
运行实例 »
点击 "运行实例" 按钮查看在线实例
View视图代码:
实例
namespace View;
class View{
public function fetch($data){
foreach ($data as $val){
return '姓名:'.$val['name'].',性别:'.$val['sex'].',年龄:'.$val['age'].',婚姻状态:'.$val['marriage'].',职业:'.$val['occupation'].',月薪:'.$val['wages'];
}
}
}
运行实例 »
点击 "运行实例" 按钮查看在线实例
Controller控制器代码:
实例
namespace Controller;
require 'Model.php';
use Model\Model;
require 'View.php';
use View\View;
$model = new Model();
$view = new View();
class Controller{
public function Index(Model $model,View $view){
$data = $model->getData();
return $view->fetch($data);
}
}
运行实例 »
点击 "运行实例" 按钮查看在线实例
入口文件:demo1.php:
实例
require 'Controller.php';
use Controller\Controller;
$controller = new Controller();
echo $controller->Index($model,$view);
运行实例 »
点击 "运行实例" 按钮查看在线实例
效果浏览图:
2、容器案例:
container 容器代码:
实例
namespace Container;
require 'Model.php';
use Model\Model;
require 'View.php';
use View\View;
class container
{
protected $rong = [];
public function bind($key,$val){
$this->rong[$key]=$val;
}
public function make($key,$valss=[])
{
return call_user_func_array($this->rong[$key],[]);
}
}
$container = new container();
$container->bind('model',function (){ return new Model();});
$container->bind('view',function (){ return new View();});
运行实例 »
点击 "运行实例" 按钮查看在线实例
Controller1 控制器代码:
实例
namespace Controller1;
require 'Container.php';
use Container\container;
class Controller1{
public function Index($container){
$data = $container->make('model')->getData();
return $container->make('view')->fetch($data);
}
}
运行实例 »
点击 "运行实例" 按钮查看在线实例
demo2.php 入口文件:
实例
require "Controller1.php";
use Controller1\Controller1;
$controller1 = new Controller1();
echo $controller1->Index($container);
运行实例 »
点击 "运行实例" 按钮查看在线实例
3、Facade 案例:
Facade.php类:
实例
namespace Facade;
require 'Container.php';
use Container\container;
class Facade
{
protected static $conrainer = null;
protected static $data = [];
public static function ini($conrainer){
static::$conrainer = $conrainer;
}
public static function getData(){
static::$data = static::$conrainer->make('model')->getData();
}
public static function fecth(){
return static::$conrainer->make('view')->fetch(static::$data);
}
}
// 继承Facade
class Student extends Facade{
}
运行实例 »
点击 "运行实例" 按钮查看在线实例
Controller2.php 控制器:
实例
namespace Controller2;
require 'Facade.php';
use Facade\Student;
class Controller2{
public function __construct($conrainer)
{
Student::ini($conrainer);
}
public function Index(){
Student::getData();
return Student::fecth();
}
}
运行实例 »
点击 "运行实例" 按钮查看在线实例
demo3.php 入口文件:
实例
require "Controller2.php";
use Controller2\Controller2;
$controller = new Controller2($container);
echo $controller->Index();
运行实例 »
点击 "运行实例" 按钮查看在线实例
4、路由实现的基本原理: