Table of Contents
下面我们拿 Yii2 做一次剖析
Home Backend Development PHP Tutorial PHP 命名空间 namespace / 类别名 use / 框架自动载入 机理的

PHP 命名空间 namespace / 类别名 use / 框架自动载入 机理的

Jun 23, 2016 pm 01:17 PM

从 php 5.3 起 PHP 多了 命名空间/延迟静态绑定/lambda匿名函数 等主要特性

命名空间的引用进一步提升了php的代码结构的灵活性和可控性,方便将项目的各工具类进行归类管理

各 php 框架则是利用命名空间做文件路径映射自动加载的功能 

下面我们拿 Yii2 做一次剖析

先看一下 Yii2的控制器书写规则

controllers\IndexController.php

<?php /** * 自动载入机制 *///==========================================================================================//声明自己的命名空间 此命名空间下的类皆归属于此命名空间管理//==========================================================================================namespace app\controllers;//==========================================================================================//use 声明其实只是为 yii\web\Controller 定义一个别名:Controller 方便我们再上下文中使用//而并非像 C/C++的include JAVA的import将导入的文件加载进来(当然php为解释语言 不存在预编译这一步)//==========================================================================================use yii\web\Controller;//==========================================================================================//IndexController的完整类名其实为 app\controller\IndexController//Controller 为 yii\web\Controller php 解释到此点才会去加载此类//==========================================================================================class IndexController extends Controller {    public function actionIndex() {        //不使用 use 提前声明 手写完整的类名        $model = new \app\models\EntryForm();//注意当前上下文中存在命名空间 所以要从根命名空间 '\' 开始    }}?>
Copy after login

1、某命名空间下的类 的完整名称为 namespace\className,当在某命名空间上下文中访问其它命名空间下的类时,我们可以使用 use 做别名化,或者使用此类的完整名称,但要以 '\' 根命名空间开头,否则解释器会认为你是在当前命名空间上下文中调用,即 foo\bar 方式会以 currentNamespace\foo\bar的方式去加载

命名空间与linux文件系统很相似,'\' 代表根,不以根开始的皆认为以当前命名空间为基点

2、use 只是给你使用的类定义短别名,use foo\bar 后则new bar() 即new \foo\bar(),还有个小技巧,当我们同时引用不同命名空间下的类名相同的类时可以使用 as 为其定义一个新别名

use foo\bar\sameName as classA;use bar\foo\sameName as classB;new classA(); // new \foo\bar\sameName;new classB(); // new \bar\foo\sameName;
Copy after login

3、当我们通过 入口文件 加载参数配置 实例化一个应用主体 加载路由组件解析请求 分派控制器调用方法时,期间会调用其他的类,比如

use yii\web\Controller;
Copy after login

系统便会去通过自动载入函数做最一次载入尝试,若仍加载不到此类则报错

下面我们看下 Yii2 从入口文件开始一个应用实体后注册自动载入函数的流程

index.php

入口文件载入配置和系统框架时会使用require调用,因为现在还没有注册自动加载函数

载入 Yii bootstrap 文件时便通过 spl_autoload_register 注册了自动载入函数 

Yii.php

Yii2的自动载入函数

继承至 BaseYii 它要做的就是根据你命名空间类型的类名去映射为此类所在的文件路径

比如 yii\web\Controller类会根据 yii 而映射到  YII2_PATH . '/web/Controller.php' 文件中,而这个文件则是命名空间为 yii\web 的 Controller 类,将此文件载入即可访问 yii\web\Controller 类

而我们自己编写的控制器或者模型则访问时为 'app\controllers\IndexController' 'app\models\EntryForm'

则 autoload 函数会根据 app 为 映射关键字将其定位到 controllers 或 models 文件夹下从而读取对应的文件即可载入相应的类,这也是为什么 类名 与 文件名 相互对应的原因所在,若不存在对应,则你只能通过固定的 require 某个文件去加载你写在其中的类了 

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

See all articles