redcatphp / mvc
此包尚未发布任何版本,信息有限。
README
以下是 MVC 基础类和模块化路由助手。
首先,如果你对这种设计模式感到不适,或者基于常见的实现有一些确信,我推荐你阅读 PHP 中 MVC 教程。
这些类非常基础,是为了扩展而定义的。它们提供了一些传统的 API、魔术方法和接口实现。
模型
模型在视图和控制之间共享,负责处理数据。
视图将使用它来访问从用户 HTTP 请求、数据库或任何其他信息来源中来的任意设置数据。
控制器将使用它来在用户 HTTP 请求的动作响应中存储数据。
以下是主要功能的示例
class MyModuleModel extends \\RedCat\\Mvc\\Model{ private $customData; function getCustomData(){ return $this->customData; } function setCustomData($data){ $this->customData = $data; } } $getter = function($id)use($db){ return $db->getRow('table',$id); }; $setter = function($id,$value)use($db){ $db->setRow('table',$id,$value); }; $model = new MyModuleModel($getter,$setter); $model['foo'] = 'bar'; echo $model['foo']; // show 'bar' if(!$model->{21}){ // call $getter $model->{21} = ['foo'=>'bar']; // call $setter } $model(); // if invokable, invoke to end set
视图
视图独立于模型或控制器,负责处理数据的表示和模板渲染。它可以由模板引擎构建,并可以访问模型以提取数据。如果它有模板引擎,它将负责选择合适的模板并将模型中的变量传递给它。
class MyModuleView extends \\RedCat\\Mvc\\View{ function assignViaCustomPresentation($vars){ // $this->model-> ... //... } } $view = new MyModuleView($model,$templateEngine); $view(); // invoke to render, it will invoke the templateEngine //or $view($template); // you can pass an optional template path to render
控制器
控制器独立于模型或视图,负责处理用户动作及其后果。控制器是模块中的可选组件,格言是“尽可能少地使用控制器”。
class MyModuleController extends \\RedCat\\Mvc\\Controller{ function action($posted){ // $this->model-> ... //... } } $controller = new MyModuleController($model); if(isset($\_POST['action'])){ $controller->action($\_POST['action']); } $controller(); // if invokable, invoke to handle $\_POST inside
路由
路由是一个 Model、一个 View 以及可选的 Controller 或甚至传递给 View 的模板引擎的结合。
$route = new \\RedCat\\Mvc\\Route($model,$view,$controller,$templateEngine); $route(); // will invoke controller (if invokable), then model (if invokable), and finally view to render
分组
分组是路由的扩展,它将 MVC 三元组组合到公共命名空间中。在以下示例中,三元组将是 MyModuleNamespace\Model、MyModuleNamespace\View 和 MyModuleNamespace\Controller。你可以选择传递一个模板引擎。
$group = new \\RedCat\\Mvc\\Group('MyModuleNamespace',$templateEngine); $group(); // then invoke it
模块
模块是分组的扩展,唯一的区别是它将为三元组类名使用前缀。
//by default prefix is 'Module\\' $module = new \\RedCat\\Mvc\\Module('MyModuleNamespace',$templateEngine); //but you can override it $module = new \\RedCat\\Mvc\\Module('MyModuleNamespace',$templateEngine,'MyNamespaceForModules\\\\'); $module(); // then invoke it