老师好, 10月11日作业如下,依赖注入/MVC/简单路由的实现,如果出现页面错误,不是因为远程服务器数据库里,没有相应的表引起的,而是因为数据库密码不同引起的。点击页面底部的php中文网图片可以返回我的博客页面,老师辛苦了,感恩感恩。 最近事很多,比较忙,而且由于纽约进入了冬令时,从而时差变为了13小时,以至于无法第一时间看直播了,但是还是会忙里偷闲看录播以及补写作业的,多谢多谢,代码如下:
依赖注入 class Model{ public function getConsole(){ return [ ['id'=>1,'name'=>'switch','brand'=>'nintendo','price'=>299], ['id'=>2,'name'=>'ps4','brand'=>'sony','price'=>399], ['id'=>3,'name'=>'xbox','brand'=>'microsoft','price'=>399], ]; } } class View{ public function fetch($data){ echo '<caption>游戏机列表</caption><br><p></p>'; $table = '<table border=1 cellspace=0 width=400>'; $table .= '<tr bgcolor="orange"><th>ID</th><th>NAME</th><th>BRAND</th><th>PRICE</th></tr>'; foreach($data as $item){ $table .= '<tr>'; $table .= ''.$item['id'].''; $table .= ''.$item['name'].''; $table .= ''.$item['brand'].''; $table .= ''.$item['price'].''; $table .= ''; } $table .= ''; return $table; } }
MVC class Cat{ public function getCat(){ return [ ['id'=>1,'name'=>'good cat','price'=>12], ['id'=>2,'name'=>'normal cat','price'=>10], ]; } } class CatView{ public function display($data){ $table = '<table border=1 cellspacing=0 width=400>'; $table .= '<caption>猫咪列表</caption>'; $table .= '<tr bgcolor="pink"><th>ID</th><th>NAME</th>PRICE'; foreach($data as $item){ $table .= '<tr>'; $table .= '<td>'.$item['id'].'</td>'; $table .= '<td>'.$item['name'].'</td>'; $table .= '<td>'.$item['price'].'</td>'; $table .= '</tr>'; } $table .= '</table>'; return $table; } } class Container{ protected $instance = []; public function bind($alias,Closure $process){ $this->instance[$alias] = $process; } public function make($alias,$params=[]){ return call_user_func_array($this->instance[$alias],[]); } } $container = new Container(); $container->bind('model',function(){ return new Cat(); }); $container->bind('view',function(){ return new CatView(); }); class Facade{ protected static $container; protected static $data = []; public static function initialize(Container $container){ static::$container = $container; } public static function getCat(){ static::$data = static::$container->make('model')->getCat(); } public static function display(){ return static::$container->make('view')->display(static::$data); } } class Kitty extends Facade{ } class Controller2{ public function __construct(Container $container) { Kitty::initialize($container); } public function index(){ Kitty::getCat(); return Kitty::display(); } } $controller2 = new Controller2($container); echo $controller2->index();
简单路由 $uri = $_SERVER['REQUEST_URI']; echo $uri; $req = explode('/',$uri); echo ''.print_r($req, true); $value = array_slice($req,3); echo ''.print_r($value,true); for($i=0;$i $params[$value[$i]] = $value[$i+1]; } echo ''.print_r($params,true); class Employee{ public function info($name,$age,$sex){ return __METHOD__.' 姓名:'.$name.' 年龄:'.$age.' 性别:'.$sex; } } echo call_user_func_array([new Employee(),'info'],$params);
作业效果图如下: