Maison développement back-end tutoriel php 构建自个儿的PHP框架-抽象框架的内容

构建自个儿的PHP框架-抽象框架的内容

Jun 13, 2016 pm 12:24 PM
application controller namespace php

构建自己的PHP框架--抽象框架的内容

上一篇博客中,我们搭建了一个最简单的框架,从单一入口的public/index.php进入,解析出相应的Controller和Action,去执行,渲染出相应的页面或者输出相应的数据。

但是我们可以看到在public/index.php文件中,是一堆代码,如果之后,我要添加权限/事件等等的机制是不是也要也在这里,那不难想象,不就的将来,index.php就会变成一个巨大无比的php文件。我们当然不想看到这样的情景,所以我们需要将这些内容抽象出来,保持入口文件的简单明了。

那我们要将这些内容抽象到那里去呢?有聪明的同学已经想到了,就是之前在composer.json中定义的位置,我们来看一下composer.json文件:

<span style="color: #000000;">{    </span>"name": "craryprimitiveman/simple-framework"<span style="color: #000000;">,    </span>"description": "A simple php framework"<span style="color: #000000;">,    </span>"license": "MIT"<span style="color: #000000;">,    </span>"authors"<span style="color: #000000;">: [        {            </span>"name": "harrysun"<span style="color: #000000;">,            </span>"email": "[email protected]"<span style="color: #000000;">        }    ],    </span>"require"<span style="color: #000000;">: {},    </span>"autoload"<span style="color: #000000;">: {        </span>"psr-4"<span style="color: #000000;">: {            </span>"sf\\": "src/"<span style="color: #000000;">,            </span>"app\\": ""<span style="color: #000000;">        }    },    </span>"repositories"<span style="color: #000000;">: [        {</span>"type": "composer", "url": "http://packagist.phpcomposer.com"<span style="color: #000000;">},        {</span>"packagist": <span style="color: #0000ff;">false</span><span style="color: #000000;">}    ]}</span>
Copier après la connexion

可以看到autoload里的psr-4里还有个sf\\,他的地址是src/,这就是我们要放抽象出的内容的地方。

有人会问,为什么不直接使用app\\ 作为namespace呢?因为想到之后要将src下的内容做成一个composer包,迁移到vendor中。

下面就正式开始抽象了。

在src下创建两个文件夹,一个是base,一个是web。base用来存放基础的类,web用来存放与web相关的类。因为将来框架可能还要支持php脚本的执行,所以要将base和web分开,将来要加php脚本时,只需要建立一个console的文件夹就好了。

在两个文件夹中分别建立Application.php文件。

先来看在base里的Application.php

<span style="color: #000000;">phpnamespace sf\base;</span><span style="color: #0000ff;">use</span> <span style="color: #0000ff;">Exception</span><span style="color: #000000;">;</span><span style="color: #008000;">/*</span><span style="color: #008000;">* * Application is the base class for all application classes. * @author Harry Sun  </span><span style="color: #008000;">*/</span><span style="color: #0000ff;">abstract</span> <span style="color: #0000ff;">class</span><span style="color: #000000;"> Application{    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * @var string the namespace that controller classes are located in.     * This namespace will be used to load controller classes by prepending it to the controller class name.     * The default namespace is `app\controllers`.     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #800080;">$controllerNamespace</span> = 'app\\controllers'<span style="color: #000000;">;    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * Runs the application.     * This is the main entrance of an application.     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> run()    {        </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {            </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$this</span>-><span style="color: #000000;">handleRequest();        } </span><span style="color: #0000ff;">catch</span> (<span style="color: #0000ff;">Exception</span> <span style="color: #800080;">$e</span><span style="color: #000000;">) {            </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$e</span><span style="color: #000000;">;        }    }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * Handles the specified request.     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">abstract</span> <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> handleRequest();}</span>
Copier après la connexion

它是一个抽象类,实现了一个简单的run方法,run方法就是去执行以下handleRequest方法。

它定义了一个抽象方法handleRequest,等待被继承,实现。

它定义了一个controllerNamespace属性,记录controller存放的namesapce,默认值是'app\\controllers'。

再来看在web里的Application.php

<span style="color: #000000;">phpnamespace sf\web;</span><span style="color: #008000;">/*</span><span style="color: #008000;">* * Application is the base class for all application classes. * @author Harry Sun  </span><span style="color: #008000;">*/</span><span style="color: #0000ff;">class</span> Application <span style="color: #0000ff;">extends</span><span style="color: #000000;"> \sf\base\Application{    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * Handles the specified request.     * @return Response the resulting response     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> handleRequest()    {        </span><span style="color: #800080;">$router</span> = <span style="color: #800080;">$_GET</span>['r'<span style="color: #000000;">];        </span><span style="color: #0000ff;">list</span>(<span style="color: #800080;">$controllerName</span>, <span style="color: #800080;">$actionName</span>) = <span style="color: #008080;">explode</span>('/', <span style="color: #800080;">$router</span><span style="color: #000000;">);        </span><span style="color: #800080;">$ucController</span> = <span style="color: #008080;">ucfirst</span>(<span style="color: #800080;">$controllerName</span><span style="color: #000000;">);        </span><span style="color: #800080;">$controllerName</span> = <span style="color: #800080;">$this</span>->controllerNamespace . '\\' . <span style="color: #800080;">$ucController</span> . 'Controller'<span style="color: #000000;">;        </span><span style="color: #800080;">$controller</span> = <span style="color: #0000ff;">new</span> <span style="color: #800080;">$controllerName</span><span style="color: #000000;">();        </span><span style="color: #0000ff;">return</span> <span style="color: #008080;">call_user_func</span>([<span style="color: #800080;">$controller</span>, 'action'. <span style="color: #008080;">ucfirst</span>(<span style="color: #800080;">$actionName</span><span style="color: #000000;">)]);    }}</span>
Copier après la connexion

是不是觉得很眼熟,其实就是将之前放在index.php中的内容放到Application的handleRequest方法里了。

然后我们需要从入口文件调用到这里的代码,这就很简单了,index.php的内容如下:

<span style="color: #000000;">php</span><span style="color: #0000ff;">require_once</span>(__DIR__ . '/../vendor/autoload.php'<span style="color: #000000;">);</span><span style="color: #800080;">$application</span> = <span style="color: #0000ff;">new</span><span style="color: #000000;"> sf\web\Application();</span><span style="color: #800080;">$application</span>->run();
Copier après la connexion

直接去new一个web Application的实例,执行run方法就可以了,是不是很简单。

访问一下:http://localhost/simple-framework/public/index.php?r=site/test,你可以看到上一次一样的结果。

 

好了,今天就先到这里。项目内容和博客内容也都会放到Github上,欢迎大家提建议。

code:https://github.com/CraryPrimitiveMan/simple-framework/tree/0.2

blog project:https://github.com/CraryPrimitiveMan/create-your-own-php-framework

 

2楼阿水
顶一记!
Re: 疯狂的原始人
@阿水,谢谢支持~~
1楼玻璃鱼儿
PHP的命名空间为什么不和JAVA amp; .NET的类似都用点号分割呢??难道不能实现吗?不可能吧。非要独树一帜,看着别扭还难受。
Re: 疯狂的原始人
@玻璃鱼儿,PHP的namespace原生是不支持用点号分割,其实稍微早一点的框架的实现,是使用点号分割的,那时候PHP还没有支持namespace。
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
2 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Repo: Comment relancer ses coéquipiers
1 Il y a quelques mois By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: Comment obtenir des graines géantes
4 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Combien de temps faut-il pour battre Split Fiction?
3 Il y a quelques semaines By DDD

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Configuration du projet CakePHP Configuration du projet CakePHP Sep 10, 2024 pm 05:25 PM

Dans ce chapitre, nous comprendrons les variables d'environnement, la configuration générale, la configuration de la base de données et la configuration de la messagerie dans CakePHP.

Guide d'installation et de mise à niveau de PHP 8.4 pour Ubuntu et Debian Guide d'installation et de mise à niveau de PHP 8.4 pour Ubuntu et Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 apporte plusieurs nouvelles fonctionnalités, améliorations de sécurité et de performances avec une bonne quantité de dépréciations et de suppressions de fonctionnalités. Ce guide explique comment installer PHP 8.4 ou mettre à niveau vers PHP 8.4 sur Ubuntu, Debian ou leurs dérivés. Bien qu'il soit possible de compiler PHP à partir des sources, son installation à partir d'un référentiel APT comme expliqué ci-dessous est souvent plus rapide et plus sécurisée car ces référentiels fourniront les dernières corrections de bogues et mises à jour de sécurité à l'avenir.

Date et heure de CakePHP Date et heure de CakePHP Sep 10, 2024 pm 05:27 PM

Pour travailler avec la date et l'heure dans cakephp4, nous allons utiliser la classe FrozenTime disponible.

Téléchargement de fichiers CakePHP Téléchargement de fichiers CakePHP Sep 10, 2024 pm 05:27 PM

Pour travailler sur le téléchargement de fichiers, nous allons utiliser l'assistant de formulaire. Voici un exemple de téléchargement de fichiers.

Routage CakePHP Routage CakePHP Sep 10, 2024 pm 05:25 PM

Dans ce chapitre, nous allons apprendre les sujets suivants liés au routage ?

Discuter de CakePHP Discuter de CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP est un framework open source pour PHP. Il vise à faciliter grandement le développement, le déploiement et la maintenance d'applications. CakePHP est basé sur une architecture de type MVC à la fois puissante et facile à appréhender. Modèles, vues et contrôleurs gu

Comment configurer Visual Studio Code (VS Code) pour le développement PHP Comment configurer Visual Studio Code (VS Code) pour le développement PHP Dec 20, 2024 am 11:31 AM

Visual Studio Code, également connu sous le nom de VS Code, est un éditeur de code source gratuit – ou environnement de développement intégré (IDE) – disponible pour tous les principaux systèmes d'exploitation. Avec une large collection d'extensions pour de nombreux langages de programmation, VS Code peut être c

CakePHP créant des validateurs CakePHP créant des validateurs Sep 10, 2024 pm 05:26 PM

Le validateur peut être créé en ajoutant les deux lignes suivantes dans le contrôleur.

See all articles