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

Use composer to implement a simple MVC architecture

Aug 09, 2019 pm 04:50 PM
composer

下面由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
Copy after login

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;
    }
}
Copy after login

在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;
    }
}
Copy after login

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

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

创建一个配置文件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;,
];
Copy after login

之后呢,在项目根目录(这里就是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();
Copy after login

从上面的代码上其是可以看到如果没有传递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
Copy after login

这个包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;
    }
}
Copy after login

测试一下,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();
    }
}
Copy after login

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

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

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

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

不支持事件和中间件

Step4 实现Model

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

  composer require illuminate/database
Copy after login

在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;
    }
}
Copy after login

这样在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;
}
Copy after login

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

<?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();
        
    }
}
Copy after login

这里有一些限制,就是无法使用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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Apr 18, 2025 am 11:48 AM

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

How to simplify email marketing with Composer: DUWA.io's application practices How to simplify email marketing with Composer: DUWA.io's application practices Apr 18, 2025 am 11:27 AM

I'm having a tricky problem when doing a mail marketing campaign: how to efficiently create and send mail in HTML format. The traditional approach is to write code manually and send emails using an SMTP server, but this is not only time consuming, but also error-prone. After trying multiple solutions, I discovered DUWA.io, a simple and easy-to-use RESTAPI that helps me create and send HTML mail quickly. To further simplify the development process, I decided to use Composer to install and manage DUWA.io's PHP library - captaindoe/duwa.

Improve Doctrine entity serialization efficiency: application of sidus/doctrine-serializer-bundle Improve Doctrine entity serialization efficiency: application of sidus/doctrine-serializer-bundle Apr 18, 2025 am 11:42 AM

I had a tough problem when working on a project with a large number of Doctrine entities: Every time the entity is serialized and deserialized, the performance becomes very inefficient, resulting in a significant increase in system response time. I've tried multiple optimization methods, but it doesn't work well. Fortunately, by using sidus/doctrine-serializer-bundle, I successfully solved this problem, significantly improving the performance of the project.

How to quickly build Fecmall advanced project templates using Composer How to quickly build Fecmall advanced project templates using Composer Apr 18, 2025 am 11:45 AM

When developing an e-commerce platform, it is crucial to choose the right framework and tools. Recently, when I was trying to build a feature-rich e-commerce website, I encountered a difficult problem: how to quickly build a scalable and fully functional e-commerce platform. I tried multiple solutions and ended up choosing Fecmall's advanced project template (fecmall/fbbcbase-app-advanced). By using Composer, this process becomes very simple and efficient. Composer can be learned through the following address: Learning address

How to view the version number of laravel? How to view the version number of laravel How to view the version number of laravel? How to view the version number of laravel Apr 18, 2025 pm 01:00 PM

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

See all articles