composer自动加载原理,laravel验证码库的使用:
项目规划:
一、实例演示类的3种加载方式:
1、传统方式: include require
<?php
// 实例演示类的3种加载方式:
// 1.传统方式: include require
//加载类文件
require_once 'app/controller/User.php';
//给类起别名
use app\controller\User;
echo User::hello();
// 输出:app\controller\User::hello
2、spl_autoload_register:
<?php
// spl_autoload_register — 注册给定的函数作为 __autoload 的实现,
// 实际上创建了 autoload 函数的队列,按定义时的顺序逐个执行。
spl_autoload_register(function($className){
echo $className;
$classFile = __DIR__ .DIRECTORY_SEPARATOR .$className . '.php';
require $classFile;
});
//给类起别名
use app\controller\User;
//调用类成员
echo User::hello();
// 输出:app\controller\Userapp\controller\User::hello
3、composer自动加载类功能:
composer.json加载三种方式:
autoload : files :可以加载任意位置的类文件:
{
"autoload": {
"files": [
"app/controller/User.php",
"lib/Order.php",
"lib/Goods.php"
]
}
}
autoload :classmap 类映射,实现类的批量注册
{
"autoload": {
"classmap": [
"app/controller",
"lib"
]
}
}
- autoload : psr-4 类的命名空间与类所在的路径目录进行绑定
{
"autoload": {
"psr-4": {
"app\\controller\\": "app/controller",
"fugen\\": "lib"
}
}
}
二、laravel验证码库的使用:
安装组件:composer require gregwar/captcha
1、composer.json:
{
"autoload": {
"psr-4": {
"app\\controller\\": "app/controller",
"fugen\\": "lib"
}
},
"require": {
"gregwar/captcha": "^1.1"
}
}
2、组件使用:
<?php
// 举例laravel验证码库的使用 composer require gregwar/captcha
require __DIR__ . '\\vendor\\autoload.php';
//注册类
use Gregwar\Captcha\CaptchaBuilder;
$builder = new CaptchaBuilder;
$builder->build();
$builder->save('yanzhengma.jpg');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>laravel验证码库</title>
</head>
<body>
<input type="text" placeholder="请输入验证码">
<img onclick="location.reload()" src="<?php echo $builder->inline(); ?>" />
</body>
</html>