下面由composer使用教程栏目为大家介绍如何运用composer实现一个简陋的MVC架构,希望对需要的朋友有所帮助!
背景缘由
网上有许多自己去编写一些类来实现MVC框架的有很多。这个是在我进行项目改造的过程中操作的手法,搭建一个简陋的MVC的简易架构其中model和view是使用的laravel中的。下列实现的方式在很多地方会跟laravel很相似哦,废话不多说,直接上步骤。(这里假设你已经安装了composer)
Step1 Composer init
直接执行composer init,按照步骤一步步下去,创建composer.json文件
使用composer可以实现类的自动加载功能,运用该功能是用来额,怎么说呢,偷懒的。将生成的composer文件按下图修改,然后按下图左边目录结构创建。
修改完配置后执行
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 'link start ^_^'; } }
创建一个配置文件config.php
return [ 'DEBUG' => true, 'timeZone' => 'Asia/Shanghai', 'APP_ROOT' => dirname(__FILE__), 'VIEW_ROOT' => dirname(__FILE__).'/app/View', ];
之后呢,在项目根目录(这里就是mvc目录)下建立一个index.php
<?php /** * Created by PhpStorm. * User: Damon * Date: 2017/12/27 * Time: 15:37 */ $config = require('./config.php'); define('APP_ROOT',$config['APP_ROOT']);//设定项目路径 define('VIEW_ROOT',$config['VIEW_ROOT']);//设定视图路径 //composer自动加载 require __DIR__ . '/vendor/autoload.php'; date_default_timezone_set($config['timeZone']);//时区设定 //获取控制器名称 if (empty($_GET["c"])) { $controller = '\App\\Controllers\\BaseController'; } else { $controller = '\App\\Controllers\\' . $_GET["c"] . 'Controller'; } $method = empty($_GET["m"]) ? 'index' : $_GET["m"];//获取方法名 $app = isAvailableController($controller, $method, $config['DEBUG']);//实例化controller echo $app->$method(); die();
从上面的代码上其是可以看到如果没有传递get参数为c的会自动调用BaseController,该控制器继承自抽象类Controller,里面有个index方法,这里直接return一个字符串link start ^_^ 。那基本上之后要调用某个控制器的某个方法就是用url来实现例如http://localhost/mvc/?c=Test&... 就是调用TestController控制器下的index方法。现在来看下是否内实现:
看来没有问题,其他比较深奥的什么路由重写啊神马的,先不考虑。
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.'/app/View']; const CACHE_PATH = APP_ROOT.'/storage/framework/cache'; public static function getView(){ $file = new Filesystem; $compiler = new BladeCompiler($file, self::CACHE_PATH); $resolver = new EngineResolver; $resolver->register('blade', 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方法
该控制器的代码如下:
namespace App\Controllers; use App\Cores\View; class TestController extends Controller { public function index() { $str = '模板在哪里啊,模板在这里。'; return View::getView()->make('index', ['str' => $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([ 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'mes', 'username' => 'root', 'password' => '12345678', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ]); // Make this Capsule instance available globally via static methods... (optional) $capsule->setAsGlobal(); // Setup the Eloquent ORM... (optional; unless you'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 = ['metal_code','metal_name','metal_type','enable','deadline']; protected $table = 'mes_metal'; 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([ 'metal_code' => 'TEST', 'metal_name' => 'test', 'materiel_type' => 1, 'enable' => 0, 'deadline' => 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!

To become a composer, you need to master music theory, harmonization, counterpoint, and be familiar with the tone and performance skills of the instrument. Composers express emotions and stories through music, and the creative process involves the construction and improvement of ideas to works.

The key steps to identifying a composer include: 1) analyzing the composer's stylistic characteristics, such as Beethoven's drama and power; 2) understanding the composer's historical background and cultural influence, such as Bach's Baroque style; 3) comprehensively analyzing the melody, harmony, rhythm and structure of the work to avoid misjudgment caused by relying solely on a single element.

Composer'sfutureinPHPdevelopmentwithAIincludes:1)AI-enhanceddependencymanagementforsuggestinglibraries,2)AI-drivencodegenerationfortailoredboilerplate,and3)predictivemaintenanceforupdatesandpatches,butfaceschallengeslikedataprivacyandAIbias.

Becoming a successful composer requires skills such as music theory, instrumental performance and sound design, as well as keen inspiration to capture and constant work modification. Composers use these skills and traits to transform emotions and thoughts into musical works, which resonates with their listeners.

Composer proficiency can be evaluated in the following four aspects: 1) Understand basic concepts, such as packages, dependencies and version control; 2) Master core functions, including parsing composer.json, solving dependencies, downloading packages and generating autoload files; 3) Proficient in using basic and advanced commands, such as composerinstall, update, require, and dump-autoload; 4) Apply best practices, such as using composer.lock files, optimizing autoload configuration, and regularly cleaning caches.

Use Composer to combine AI to achieve automated tasks. 1. Composer manages dependencies through configuration file, and AI can optimize version selection. 2. In practical applications, AI can be used to automate dependency management, testing and deployment. 3. Performance optimization includes dependency loading and caching strategies. 4. Pay attention to issues such as version conflicts and AI misjudgment. Through these methods, AI can improve work efficiency and intelligence.

ComposerwithAI is a tool that uses AI to improve the programming experience. 1) It provides real-time suggestions and bug fixes by analyzing code structure, syntax and pattern. 2) Advanced features include code refactoring, performance optimization and security checking. 3) When using, you can adjust the configuration, provide feedback and combine other tools to solve common problems.

Composer is a dependency management tool for PHP, which is used to manage libraries and packages required by projects. 1) It defines dependencies through composer.json file, 2) installs and updates using command line tools, 3) automates the dependency management process, improves development efficiency, 4) supports advanced functions such as dynamically adding dependencies and automatic loading, 5) Ensures consistency of the team environment through composer.lock file.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version
Chinese version, very easy to use

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
