Preface
Laravel frameworkBecause of its componentized design and proper use of design Patterns make the framework itself concise and easy to extend. Different from ThinkPHP's integrated function framework (either all functions are used or none), Laravel uses the composer tool to manage packages. If you want to add functions, you can directly add components. For example, if you write a crawler and use the page collection component: composer require jaeger/querylist
This article briefly introduces the PHP features and new syntax frequently used in Laravel. Please refer to it for details.
Component-based development
Laravel performs component-based development thanks to the composer tool that follows the PSR-4 specification, which uses namespaces and automatic loading to organize project files. More reference: composer automatic loading mechanism
Namespace
Name conflict
When collaborating in a team and introducing third-party dependent code, classes, functions and interfaces may often appear Duplicate names. For example:
<?php # google.php class User { private $name; }
<?php # mine.php // 引入第三方依赖 include 'google.php'; class User { private $name; } $user = new User(); // 命名冲突
Name conflict occurs because the class User
is defined at the same time:
naming conflicts and to keep names short. For example, after using the namespace:
<?php # google.php namespace Google; // 模拟第三方依赖 class User { private $name = 'google'; public function getName() { echo $this->name . PHP_EOL; } }
<?php # mine.php namespace Mine; // 导入并命名别名 use Google as G; // 导入文件使得 google.php 命名空间变为 mine.php 的子命名空间 include 'google.php'; /* 避免了命名冲突 */ class User { private $name = 'mine'; public function getName() { echo $this->name . PHP_EOL; } } /* 保持了命名简短 */ // 如果没有命名空间,为了类名也不冲突,可能会出现这种函数名 // $user = new Google_User(); // Zend 风格并不提倡 $user = new G\User(); // 为了函数名也不冲突,可能会出现这种函数名 // $user->google_get_name() $user->getName(); $user = new User(); $user->getName();Run:
$ php demo.php google minePSR specificationIn fact, the namespace has nothing to do with the file name, but according to the PSR standard requirements: the namespace is consistent with the file path& The file name is consistent with the class name. For example,
laravel-demo/app/Http/Controllers/Auth/LoginController.php generated by Laravel by default, its namespace is
App\Http\Controllers\Auth & class name
LoginController
mine.php and
google.php should both be called
User.php
__NAMESPACE__ Magic constants
...
// $user = new User();
$user = new namespace\User(); // 值为当前命名空间
$user->getName();
echo __NAMESPACE__ . PHP_EOL; // 直接获取当前命名空间字符串 // 输出 Mine
Import of three namespaces<?php namespace CurrentNameSpace;
// 不包含前缀
$user = new User(); # CurrentNameSpace\User();
// 指定前缀
$user = new Google\User(); # CurrentNameSpace\Google\User();
// 根前缀
$user = new \Google\User(); # \Google\User();
Global namespaceIf the referenced class, If the function does not specify a namespace, it will be searched under __NAMESPACE__ by default. To reference the global class:
<?php namespace Demo; // 均不会被使用到 function strlen() {} const INI_ALL = 3; class Exception {} $a = \strlen('hi'); // 调用全局函数 strlen $b = \CREDITS_GROUP; // 访问全局常量 CREDITS_GROUP $c = new \Exception('error'); // 实例化全局类 ExceptionMultiple imports and multiple namespaces
// use 可一次导入多个命名空间
use Google,
Microsoft;
// 良好实践:每行一个 use
use Google;
use Microsoft;
<?php // 一个文件可定义多个命名空间
namespace Google {
class User {}
}
namespace Microsoft {
class User {}
}
// 良好实践:“一个文件一个类”
Import constants and functionsStarting from PHP 5.6, you can use use function and
use const Import functions and constants respectively. Use:
# google.php const CEO = 'Sundar Pichai'; function getMarketValue() { echo '770 billion dollars' . PHP_EOL; }
# mine.php use function Google\getMarketValue as thirdMarketValue; use const Google\CEO as third_CEO; thirdMarketValue(); echo third_CEO;Run:
$ php mine.php google 770 billion dollars Sundar Pichaimine MineFile containsManual loading Use
include or
require to introduce the specified file. (Literal interpretation) Please note that a require error will report a compilation error and interrupt the script, while an include error will only report a warning and the script will continue to run.
include_path in php.ini. If it cannot find it, it will search in the current directory:
<?php // 引入的是 /usr/share/php/System.php include 'System.php';Automatic loading
void __autoload(string $class) can automatically load classes, but generally use spl_autoload_register to register manually:
<?php // 自动加载子目录 classes 下 *.class.php 的类定义 function __autoload($class) { include 'classes/' . $class . '.class.php'; } // PHP 5.3 后直接使用匿名函数注册 $throw = true; // 注册出错时是否抛出异常 $prepend = false; // 是否将当前注册函数添加到队列头 spl_autoload_register(function ($class) { include 'classes/' . $class . '.class.php'; }, $throw, $prepend);In the autoloading file generated by composer
laravel-demo/vendor/composer/autoload_real.php you can see:
class ComposerAutoloaderInit8b41a { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { // 加载当前目录下文件 require __DIR__ . '/ClassLoader.php'; } } public static function getLoader() { if (null !== self::$loader) { return self::$loader; } // 注册自己的加载器 spl_autoload_register(array('ComposerAutoloaderInit8b41a6', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(); spl_autoload_unregister(array('ComposerAutoloaderInit8b41a6a', 'loadClassLoader')); ... } ... }I will only mention here, specifically how Laravel does automatic loading as a whole Yes, the following articles will elaborate on it. ReflectionRefer to the PHP manual, which can be simply understood as obtaining the complete information of the object at runtime. There are 5 classes of reflection:
ReflectionClass // 解析类名 ReflectionProperty // 获取和设置类属性的信息(属性名和值、注释、访问权限) ReflectionMethod // 获取和设置类函数的信息(函数名、注释、访问权限)、执行函数等 ReflectionParameter // 获取函数的参数信息 ReflectionFunction // 获取函数信息For example, the use of
ReflectionClass:
<?php class User { public $name; public $age; public function __construct($name = 'Laruence', $age = 35) { $this->name = $name; $this->age = $age; } public function intro() { echo '[name]: ' . $this->name . PHP_EOL; echo '[age]: ' . $this->age . PHP_EOL; } } reflect('User'); // ReflectionClass 反射类使用示例 function reflect($class) { try { $ref = new ReflectionClass($class); // 检查是否可实例化 // interface、abstract class、 __construct() 为 private 的类均不可实例化 if (!$ref->isInstantiable()) { echo "[can't instantiable]: ${class}\n"; } // 输出属性列表 // 还能获取方法列表、静态常量等信息,具体参考手册 foreach ($ref->getProperties() as $attr) { echo $attr->getName() . PHP_EOL; } // 直接调用类中的方法,个人认为这是反射最好用的地方 $obj = $ref->newInstanceArgs(); $obj->intro(); } catch (ReflectionException $e) { // try catch 机制真的不优雅 // 相比之下 Golang 的错误处理虽然繁琐,但很简洁 echo '[reflection exception: ]' . $e->getMessage(); } }Run:
$ php reflect.php name age [name]: Laruence [age]: 35For the other four reflection classes, please refer to the manual demo . Late static bindingRefer to the PHP manual and look at an example first:
<?php class Base { // 后期绑定不局限于 static 方法 public static function call() { echo '[called]: ' . __CLASS__ . PHP_EOL; } public static function test() { self::call(); // self 取值为 Base 直接调用本类中的函数 static::call(); // static 取值为 Child 调用者 } } class Child extends Base { public static function call() { echo '[called]: ' . __CLASS__ . PHP_EOL; } } Child::test();Output:
$ php late_static_bind.php [called]: Base [called]: ChildWhen the object is instantiated,
self:: will instantiate the class in which it is defined,
static:: will instantiate the class that calls it.
<?php class DemoLogger { public function log($message, $level) { echo "[message]: $message", PHP_EOL; echo "[level]: $level", PHP_EOL; } } trait Loggable { protected $logger; public function setLogger($logger) { $this->logger = $logger; } public function log($message, $level) { $this->logger->log($message, $level); } } class Foo { // 直接引入 Loggable 的代码片段 use Loggable; } $foo = new Foo; $foo->setLogger(new DemoLogger); $foo->log('trait works', 1);Run:
$ php trait.php [message]: trait works [level]: 1More reference: What I understand about PHP TraitImportant propertiesPriority The function of the current class will overwrite the function of the same name of the trait, and the trait will overwrite the function of the same name of the parent class (
use trait is equivalent to the current class directly overwriting the function of the same name of the parent class)
,, that is, multiple inheritance.
多个 trait 有同名函数时,引入将发生命名冲突,使用 insteadof
来指明使用哪个 trait 的函数。
重命名与访问控制
使用 as
关键字可以重命名的 trait 中引入的函数,还可以修改其访问权限。
其他
trait 类似于类,可以定义属性、方法、抽象方法、静态方法和静态属性。
下边的苹果、微软和 Linux 的小栗子来说明:
<?php trait Apple { public function getCEO() { echo '[Apple CEO]: Tim Cook', PHP_EOL; } public function getMarketValue() { echo '[Apple Market Value]: 953 billion', PHP_EOL; } } trait MicroSoft { public function getCEO() { echo '[MicroSoft CEO]: Satya Nadella', PHP_EOL; } public function getMarketValue() { echo '[MicroSoft Market Value]: 780 billion', PHP_EOL; } abstract public function MadeGreatOS(); static public function staticFunc() { echo '[MicroSoft Static Function]', PHP_EOL; } public function staticValue() { static $v; $v++; echo '[MicroSoft Static Value]: ' . $v, PHP_EOL; } } // Apple 最终登顶,成为第一家市值超万亿美元的企业 trait Top { // 处理引入的 trait 之间的冲突 use Apple, MicroSoft { Apple::getCEO insteadof MicroSoft; Apple::getMarketValue insteadof MicroSoft; } } class Linux { use Top { // as 关键字可以重命名函数、修改权限控制 getCEO as private noCEO; } // 引入后必须实现抽象方法 public function MadeGreatOS() { echo '[Linux Already Made]', PHP_EOL; } public function getMarketValue() { echo '[Linux Market Value]: Infinity', PHP_EOL; } } $linux = new Linux(); // 和 extends 继承一样 // 当前类中的同名函数也会覆盖 trait 中的函数 $linux->getMarketValue(); // trait 中可以定义静态方法 $linux::staticFunc(); // 在 trait Top 中已解决过冲突,输出库克 $linux->getCEO(); // $linux->noCEO(); // Uncaught Error: Call to private method Linux::noCEO() // trait 中可以定义静态变量 $linux->staticValue(); $linux->staticValue();
运行:
$ php trait.php [Linux Market Value]: Infinity [MicroSoft Static Function] [Apple CEO]: Tim Cook [MicroSoft Static Value]: 1 [MicroSoft Static Value]: 2
总结
本节简要提及了命名空间、文件自动加载、反射机制与 trait 等,Laravel 正是恰如其分的利用了这些新特性,才实现了组件化开发、服务加载等优雅的特性。