Home  >  Article  >  PHP Framework  >  Summarize what PHP syntax is commonly used in Laravel

Summarize what PHP syntax is commonly used in Laravel

藏色散人
藏色散人forward
2021-09-09 11:28:262091browse

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 &#39;google.php&#39;;

class User
{
    private $name;
}

$user = new User();    // 命名冲突

Name conflict occurs because the class User is defined at the same time:

Summarize what PHP syntax is commonly used in Laravel

##Solution

From PHP 5.3 Start the introduction. Refer to the PHP manual to know that namespace has two functions: to avoid

naming conflicts and to keep names short. For example, after using the namespace:

<?php # google.php
namespace Google;

// 模拟第三方依赖
class User {
    private $name = &#39;google&#39;;

    public function getName() {
        echo $this->name . PHP_EOL;
    }
}
<?php # mine.php
namespace Mine;

// 导入并命名别名
use Google as G;

// 导入文件使得 google.php 命名空间变为 mine.php 的子命名空间
include &#39;google.php&#39;;

/* 避免了命名冲突 */
class User
{
    private $name = &#39;mine&#39;;

    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
mine
PSR specification

In 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

Follow the specifications, the above

mine.php and google.php should both be called User.php

namespace operator and

__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 namespace

If 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(&#39;hi&#39;);         // 调用全局函数 strlen
$b = \CREDITS_GROUP;          // 访问全局常量 CREDITS_GROUP
$c = new \Exception(&#39;error&#39;);   // 实例化全局类 Exception
Multiple 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 functions

Starting 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
Mine
File contains

Manual 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 file, it will first search in the directory specified by the configuration item

include_path in php.ini. If it cannot find it, it will search in the current directory:

Summarize what PHP syntax is commonly used in Laravel

<?php     
// 引入的是 /usr/share/php/System.php
include &#39;System.php&#39;;
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 &#39;classes/&#39; . $class . &#39;.class.php&#39;;
}

// PHP 5.3 后直接使用匿名函数注册
$throw = true;        // 注册出错时是否抛出异常
$prepend = false;    // 是否将当前注册函数添加到队列头

spl_autoload_register(function ($class) {
    include &#39;classes/&#39; . $class . &#39;.class.php&#39;;
}, $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.

Reflection

Refer 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 = &#39;Laruence&#39;, $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]: 35
For the other four reflection classes, please refer to the manual demo .

Late static binding

Refer to the PHP manual and look at an example first:

<?php class Base
{
        // 后期绑定不局限于 static 方法
    public static function call() {
        echo &#39;[called]: &#39; . __CLASS__ . PHP_EOL;
    }

    public static function test() {
        self::call();        // self   取值为 Base  直接调用本类中的函数
        static::call();        // static 取值为 Child 调用者
    }
}

class Child extends Base
{
    public static function call() {
        echo &#39;[called]: &#39; . __CLASS__ . PHP_EOL;
    }
}


Child::test();
Output:

$ php late_static_bind.php
[called]: Base
[called]: Child
When the object is instantiated,

self:: will instantiate the class in which it is defined, static:: will instantiate the class that calls it.

trait

Basic usage

Refer to the PHP manual. Although PHP is single-inherited, from 5.4 onwards, "classes" can be realized by horizontally combining "classes" through traits. Multiple inheritance is actually to split the repeated functions into triats and put them in different files, and introduce and combine them as needed through the use keyword. Inheritance can be implemented by analogy to Golang's struct cramming combination. For example:

<?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]: 1
More reference: What I understand about PHP Trait

Important properties

Priority

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)

trait function Conflict

Introduction of multiple traits at the same time can be separated by

,, that is, multiple inheritance.

多个 trait 有同名函数时,引入将发生命名冲突,使用 insteadof 来指明使用哪个 trait 的函数。

重命名与访问控制

使用 as 关键字可以重命名的 trait 中引入的函数,还可以修改其访问权限。

其他

trait 类似于类,可以定义属性、方法、抽象方法、静态方法和静态属性。

下边的苹果、微软和 Linux 的小栗子来说明:

<?php trait Apple
{
    public function getCEO() {
        echo &#39;[Apple CEO]: Tim Cook&#39;, PHP_EOL;
    }

    public function getMarketValue() {
        echo &#39;[Apple Market Value]: 953 billion&#39;, PHP_EOL;
    }
}


trait MicroSoft
{
    public function getCEO() {
        echo &#39;[MicroSoft CEO]: Satya Nadella&#39;, PHP_EOL;
    }

    public function getMarketValue() {
        echo &#39;[MicroSoft Market Value]: 780 billion&#39;, PHP_EOL;
    }

    abstract public function MadeGreatOS();

    static public function staticFunc() {
        echo &#39;[MicroSoft Static Function]&#39;, PHP_EOL;
    }

    public function staticValue() {
        static $v;
        $v++;
        echo &#39;[MicroSoft Static Value]: &#39; . $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 &#39;[Linux Already Made]&#39;, PHP_EOL;
    }

    public function getMarketValue() {
        echo &#39;[Linux Market Value]: Infinity&#39;, 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 正是恰如其分的利用了这些新特性,才实现了组件化开发、服务加载等优雅的特性。

The above is the detailed content of Summarize what PHP syntax is commonly used in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:wuYin/blog. If there is any infringement, please contact admin@php.cn delete