Home Backend Development PHP Tutorial PHP namespace autoloading: How to use composer's autoload to achieve automatic loading

PHP namespace autoloading: How to use composer's autoload to achieve automatic loading

May 22, 2017 am 11:22 AM

在 PHP5 以后的版本中可以定义一个 __autoload() 函数,当调用一个未定义的类的时候就会启动此函数,从而在抛出错误之前做最后的补救,不过这个函数的本意已经被完全曲解使用了,现在都用来做自动加载。后来这个函数实际上已经不被推荐使用了,相反,现在应当使用 spl_autoload_register() 来注册类的自动加载函数。前面我们介绍了php命名空间的基本知识,使用方法,作用等等,这一节就重点来说说php命名空间自动加载。

spl_autoload_register() 的语法格式如下:

bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )
Copy after login

autoload_function 是需要注册的自动装载函数,如果此项为空,则会注册 spl_autoload 函数,

throw 此参数设置了 autoload_function 无法成功注册时, spl_autoload_register() 是否抛出异常。

prepend 如果是 true, spl_autoload_register() 会添加函数到队列之首,而不是队列尾部。

上面提到了 spl_autoload 函数,实际上注册函数的规范就应当遵循此函数,函数声明如下:

void spl_autoload ( string $class_name [, string $file_extensions ] )
Copy after login

由于这个函数默认实现是通过 C 语言,所以这里给出一个 PHP 语言的实现规范。

其实例代码如下:

<?php
// 自定义类
define(&#39;CLASS_DIR&#39;, &#39;class/&#39;);
// 添加类的路径
set_include_path(get_include_path().PATH_SEPARATOR.CLASS_DIR);
// 使用自动加载添加类
spl_autoload_extensions(&#39;.class.php&#39;);
// 默认加载
spl_autoload_register();
?>
Copy after login

大致上就和这个是类似的。实际上命名空间和自动加载类的结合就基本是通过路径形式。

使用composer的autoload来自动加载

composer的出现真是让人们眼前一亮,web开发从此变成了一件很“好玩”的事情,开发一个CMS就像在搭积木,从packagist中取出“ 积木 ”搭建在自己的代码中,一点一点搭建出一个属于自己的王国。

使用composer基本就可以抛弃了require和include函数,一个项目中,这两个函数只可能出现一次,那就是 require '../vendor/autoload.php'。

然后就可以非常方便的去使用第三方的类库了,是不是感觉很棒啊!对于我们需要的monolog,就可以这样用了:

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
// 创建日志
$log = new Logger(&#39;name&#39;);
$log->pushHandler(new StreamHandler(&#39;/path/to/log/log_name.log&#39;, Logger::WARNING));
// 将记录添加到日志
$log->addWarning(&#39;Foo&#39;);
$log->addError(&#39;Bar&#39;);
Copy after login

在这个过程中,Composer做了什么呢?它生成了一个autoloader,再根据各个包自己的autoload配置,从而帮我们进行自动加载的工作。

实现方式的步骤:

1. 先安装composer,可以参照php依赖管理工具composer入门教程

2. 在项目根目录创建composer.json文件,写入代码

{
    "type": "project",
    "autoload": {
        "psr-4": {
            "Admin\\": "admin/"
        }
    }
}
Copy after login

3. 在项目根目录打开命令,写入命令

composer update
Copy after login

4.等待执行完成。安装成功后,会在项目根目录下新建一个"/vendor/"文件夹。

说明:使用之前需要require一下"/vendor/autoload.php"文件。

$autoLoadFilePath = dirname($_SERVER[&#39;DOCUMENT_ROOT&#39;]).DIRECTORY_SEPARATOR.&#39;vendor&#39;.DIRECTORY_SEPARATOR.&#39;autoload.php&#39;;
require_once $autoLoadFilePath;
Copy after login

5. 在"/admin/"目录下新建test.php文件,文件内容如下

<?php
namespace Admin;
class test
{
   public function sayHi()
   {
       echo &#39;hi&#39;;
   }
}
?>
Copy after login

在"/public/"目录下新建index.php文件,文件内容如下

sayHi();
?>
Copy after login

6. 配置apache,访问路径,得到如下的结果就表示成功。

PHP namespace autoloading: How to use composers autoload to achieve automatic loading

【相关教程推荐】

1. 《php.cn独孤九贱(4)-php视频教程

2.  视频教程:命名空间:我们虽然同名同性,但却属于不同时空

3.  php编程从入门到精通全套教程

The above is the detailed content of PHP namespace autoloading: How to use composer's autoload to achieve automatic loading. 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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
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)

Composer's advanced features: aliases, scripts, and conflict resolution Composer's advanced features: aliases, scripts, and conflict resolution Jun 03, 2024 pm 12:37 PM

Composer provides advanced features, including: 1. Aliases: define convenient names for packages for repeated reference; 2. Scripts: execute custom commands when installing/updating packages, used to create database tables or compile resources; 3. Conflict resolution: use priorities Rules, satisfaction constraints, and package aliases resolve the different requirements of multiple packages for the same dependency version to avoid installation conflicts.

Agile development and operation of PHP microservice containerization Agile development and operation of PHP microservice containerization May 08, 2024 pm 02:21 PM

Answer: PHP microservices are deployed with HelmCharts for agile development and containerized with DockerContainer for isolation and scalability. Detailed description: Use HelmCharts to automatically deploy PHP microservices to achieve agile development. Docker images allow for rapid iteration and version control of microservices. The DockerContainer standard isolates microservices, and Kubernetes manages the availability and scalability of the containers. Use Prometheus and Grafana to monitor microservice performance and health, and create alarms and automatic repair mechanisms.

The role of PHP CI/CD in DevOps projects The role of PHP CI/CD in DevOps projects May 08, 2024 pm 09:09 PM

PHPCI/CD is a key practice in DevOps projects that automates the build, test, and deployment processes to improve development efficiency and software quality. A typical PHPCI/CD pipeline consists of the following stages: 1) Continuous Integration: Whenever the code changes, the code is automatically built and tested. 2) Continuous deployment: Speed ​​up delivery by automatically deploying tested and integrated code to the production environment. By implementing the PHPCI/CD pipeline, you can increase development efficiency, improve software quality, shorten time to market, and improve reliability.

PHP code version control and collaboration PHP code version control and collaboration May 07, 2024 am 08:54 AM

PHP code version control: There are two version control systems (VCS) commonly used in PHP development: Git: distributed VCS, where developers store copies of the code base locally to facilitate collaboration and offline work. Subversion: Centralized VCS, a unique copy of the code base is stored on a central server, providing more control. VCS helps teams track changes, collaborate and roll back to earlier versions.

Visualization technology of PHP data structure Visualization technology of PHP data structure May 07, 2024 pm 06:06 PM

There are three main technologies for visualizing data structures in PHP: Graphviz: an open source tool that can create graphical representations such as charts, directed acyclic graphs, and decision trees. D3.js: JavaScript library for creating interactive, data-driven visualizations, generating HTML and data from PHP, and then visualizing it on the client side using D3.js. ASCIIFlow: A library for creating textual representation of data flow diagrams, suitable for visualization of processes and algorithms.

How to use PHP CI/CD to iterate quickly? How to use PHP CI/CD to iterate quickly? May 08, 2024 pm 10:15 PM

Answer: Use PHPCI/CD to achieve rapid iteration, including setting up CI/CD pipelines, automated testing and deployment processes. Set up a CI/CD pipeline: Select a CI/CD tool, configure the code repository, and define the build pipeline. Automated testing: Write unit and integration tests and use testing frameworks to simplify testing. Practical case: Using TravisCI: install TravisCI, define the pipeline, enable the pipeline, and view the results. Implement continuous delivery: select deployment tools, define deployment pipelines, and automate deployment. Benefits: Improve development efficiency, reduce errors, and shorten delivery time.

How to use Redis cache in PHP array pagination? How to use Redis cache in PHP array pagination? May 01, 2024 am 10:48 AM

Using Redis cache can greatly optimize the performance of PHP array paging. This can be achieved through the following steps: Install the Redis client. Connect to the Redis server. Create cache data and store each page of data into a Redis hash with the key "page:{page_number}". Get data from cache and avoid expensive operations on large arrays.

How does Composer handle the composer.lock file? How does Composer handle the composer.lock file? Jun 03, 2024 pm 04:40 PM

Composer manages dependencies by using the composer.lock file, which records all installed dependencies and their exact versions, making it: Ensure consistency and avoid version conflicts. Improve performance without having to search for packages repeatedly. Track changes, recording installed dependency versions after each install command.

See all articles