Home >Development Tools >composer >Use composer to implement a simple MVC architecture

Use composer to implement a simple MVC architecture

藏色散人
藏色散人forward
2019-08-09 16:50:343229browse

下面由composer使用教程栏目为大家介绍如何运用composer实现一个简陋的MVC架构,希望对需要的朋友有所帮助!

Use composer to implement a simple MVC architecture

背景缘由

网上有许多自己去编写一些类来实现MVC框架的有很多。这个是在我进行项目改造的过程中操作的手法,搭建一个简陋的MVC的简易架构其中model和view是使用的laravel中的。下列实现的方式在很多地方会跟laravel很相似哦,废话不多说,直接上步骤。(这里假设你已经安装了composer)

Step1 Composer init

直接执行composer init,按照步骤一步步下去,创建composer.json文件

Use composer to implement a simple MVC architecture

使用composer可以实现类的自动加载功能,运用该功能是用来额,怎么说呢,偷懒的。将生成的composer文件按下图修改,然后按下图左边目录结构创建。

Use composer to implement a simple MVC architecture

修改完配置后执行

composer install
composer dump-autoload

Step 2 构建一些基本文件及功能

之后在helper.php文件中添加一个函数,该函数是判断函数及其controller存在与否

if (!function_exists('isAvailableController')) {
    function isAvailableController($controller,$method,$debug)
    {
        if(class_exists($controller)){
            $app =$controller::getinstance();
            //判断调用的方法控制器类中是否存在
            if(!method_exists($controller,$method)){
                echo $controller.'类不存在'.$method.'方法!';
                die();
            }
        } else {
            echo $controller.'类不存在!';
            die();
        }
        return $app;
    }
}

在Controllers目录下新建一个Controller作为抽象类

<?php
/**
 * Created by PhpStorm.
 * User: Damon
 * Date: 2017/12/26
 * Time: 2017/12/26
 * Info: basic controller
 */
namespace App\Controllers;
abstract class Controller
{
    protected static $instance = null;
    final protected function __construct(){
        $this->init();
    }
    final protected function __clone(){}
    protected function init(){}
    //abstract protected function init();
    public static function getInstance(){
        if(static::$instance === null){
            static::$instance = new static();
        }
        return static::$instance;
    }
}

之后在Controllers目录下新建控制器就行了,例如我实现一个TestController,请注意新建的控制器必须以Controller结尾并继承上面的Controller,如下:

namespace App\Controllers;
class TestController extends Controller
{
    public function index()
    {
        echo &#39;link start ^_^&#39;;
    }
}

创建一个配置文件config.php

return [
    &#39;DEBUG&#39; => true,
    &#39;timeZone&#39; => &#39;Asia/Shanghai&#39;,
    &#39;APP_ROOT&#39; => dirname(__FILE__),
    &#39;VIEW_ROOT&#39; => dirname(__FILE__).&#39;/app/View&#39;,
];

之后呢,在项目根目录(这里就是mvc目录)下建立一个index.php

<?php
/**
 * Created by PhpStorm.
 * User: Damon
 * Date: 2017/12/27
 * Time: 15:37
 */
$config = require(&#39;./config.php&#39;);
define(&#39;APP_ROOT&#39;,$config[&#39;APP_ROOT&#39;]);//设定项目路径
define(&#39;VIEW_ROOT&#39;,$config[&#39;VIEW_ROOT&#39;]);//设定视图路径
//composer自动加载
require __DIR__ . &#39;/vendor/autoload.php&#39;;
date_default_timezone_set($config[&#39;timeZone&#39;]);//时区设定
//获取控制器名称
if (empty($_GET["c"])) {
    $controller = &#39;\App\\Controllers\\BaseController&#39;;
} else {
    $controller = &#39;\App\\Controllers\\&#39; . $_GET["c"] . &#39;Controller&#39;;
}
$method = empty($_GET["m"]) ? &#39;index&#39; : $_GET["m"];//获取方法名
$app = isAvailableController($controller, $method, $config[&#39;DEBUG&#39;]);//实例化controller
echo $app->$method();
die();

从上面的代码上其是可以看到如果没有传递get参数为c的会自动调用BaseController,该控制器继承自抽象类Controller,里面有个index方法,这里直接return一个字符串link start ^_^ 。那基本上之后要调用某个控制器的某个方法就是用url来实现例如http://localhost/mvc/?c=Test&... 就是调用TestController控制器下的index方法。现在来看下是否内实现:

Use composer to implement a simple MVC architecture

看来没有问题,其他比较深奥的什么路由重写啊神马的,先不考虑。

Step3 实现模板引擎

这里实现模板引擎的方式是使用laravel的blade模板引擎,如何引入呢,这里使用composer来引入一个包来解决。

composer require xiaoler/blade

这个包git上有比较详细的说明,这个是xiaoler/blade包的连接

引入完这个包怎么实现模板引擎呢,我自己是根据包的说明实现了一个View类把他放到Cores目录下内容如下:

namespace App\Cores;
use Xiaoler\Blade\FileViewFinder;
use Xiaoler\Blade\Factory;
use Xiaoler\Blade\Compilers\BladeCompiler;
use Xiaoler\Blade\Engines\CompilerEngine;
use Xiaoler\Blade\Filesystem;
use Xiaoler\Blade\Engines\EngineResolver;
class View
{
    const VIEW_PATH = [APP_ROOT.&#39;/app/View&#39;];
    const CACHE_PATH = APP_ROOT.&#39;/storage/framework/cache&#39;;
    public static function getView(){
        $file = new Filesystem;
        $compiler = new BladeCompiler($file, self::CACHE_PATH);
        $resolver = new EngineResolver;
        $resolver->register(&#39;blade&#39;, function () use ($compiler) {
            return new CompilerEngine($compiler);
        });
        $factory = new Factory($resolver, new FileViewFinder($file, self::VIEW_PATH));
        return $factory;
    }
}

测试一下,http://localhost/mvc/?c=Test&...,也就是调用TestController的index方法

Use composer to implement a simple MVC architecture

该控制器的代码如下:

namespace App\Controllers;
use App\Cores\View;
class TestController extends Controller
{
    public function index()
    {
        $str = &#39;模板在哪里啊,模板在这里。&#39;;
        return View::getView()->make(&#39;index&#39;, [&#39;str&#39; => $str])->render();
    }
}

控制器中调用的模板是index.blade.php,内容如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>home view</title>
</head>
<body>
{{ $str }}
</body>
</html>

模板引擎功能OK啦,之后就可以愉快地使用blade模板引擎了,不过有些laravel中自带的一些语法是不能用的哦,该包的git上有说明这里引用下

@inject @can @cannot @lang 关键字被移除了

不支持事件和中间件

Step4 实现Model

这里使用的是illuminate / database包来实现Model的,执行以下命令安装。

  composer require illuminate/database

在Core目录下新建一个DB类,代码如下:

<?php
/**
 * Created by PhpStorm.
 * User: Damon
 * Date: 2017/12/28
 * Time: 9:13
 */
namespace App\Cores;
use Illuminate\Database\Capsule\Manager as Capsule;
class DB
{
    protected static $instance = null;
    final protected function __construct(){
        $this->init();
    }
    final protected function __clone(){}
    protected function init(){
        $capsule = new Capsule;
        $capsule->addConnection([
            &#39;driver&#39; => &#39;mysql&#39;,
            &#39;host&#39; => &#39;localhost&#39;,
            &#39;database&#39; => &#39;mes&#39;,
            &#39;username&#39; => &#39;root&#39;,
            &#39;password&#39; => &#39;12345678&#39;,
            &#39;charset&#39; => &#39;utf8&#39;,
            &#39;collation&#39; => &#39;utf8_unicode_ci&#39;,
            &#39;prefix&#39; => &#39;&#39;,
        ]);
        // Make this Capsule instance available globally via static methods... (optional)
        $capsule->setAsGlobal();
        // Setup the Eloquent ORM... (optional; unless you&#39;ve used setEventDispatcher())
        $capsule->bootEloquent();
    }
    //abstract protected function init();
    public static function linkStart(){
        if(static::$instance === null){
            static::$instance = new static();
        }
        return static::$instance;
    }
}

这样在controller中就可以使用了,例如先在app目录下建立Model目录,在Model中新建一个Model文件Matter.php。

<?php
/**
 * Created by PhpStorm.
 * User: Damon
 * Date: 2017/12/28
 * Time: 9:52
 */
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Metal extends Model
{
    protected $fillable = [&#39;metal_code&#39;,&#39;metal_name&#39;,&#39;metal_type&#39;,&#39;enable&#39;,&#39;deadline&#39;];
    protected $table = &#39;mes_metal&#39;;
    public $timestamps = false;
}

之后可以在控制器中这么使用:

<?php
/**
 * Created by PhpStorm.
 * User: Damon
 * Date: 2017/12/27
 * Time: 16:08
 */
namespace App\Controllers;
use App\Cores\DB;
use App\Cores\View;
use App\Model\Metal;
class TestController extends Controller
{
    public function index()
    {
        DB::linkStart();//连接db
        Metal::create([
            &#39;metal_code&#39; => &#39;TEST&#39;,
            &#39;metal_name&#39; => &#39;test&#39;,
            &#39;materiel_type&#39; => 1,
            &#39;enable&#39; => 0,
            &#39;deadline&#39; => 30
        ]);
        $res= Metal::all()->toArray();
        var_dump($res);
        die();
        
    }
}

这里有一些限制,就是无法使用laravel中的DB::connect(),不过其他的基础使用好像都可以。并且这里无法切换连接的数据库,这个其实可以将DB类进行修改,至于如何修改,自己想吧。

The above is the detailed content of Use composer to implement a simple MVC architecture. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete