PHP Reload and laravel façade facade

Source: Internet
Author: User

Tag: Just return Data save Data demo start GPO bug down

[TOC]
Laravel offers a lot of easy-to-use facade, so let's get it right, so what are these facade principles?
In fact, the use of PHP overload.

The concept of overloading

PHP provides a "reload" (overloading) that refers to the dynamic "create" class properties and methods.

In PHP, it is done by means of magic methods. In C++/java, overloading refers to a method in which multiple names in a class are identical and the list of parameter types is not the same. The meta-table in Lua is similar to the overloaded concept of PHP, for students who have studied C++/java can take the overload of PHP as a new concept, without having to tangle with the difference between why and C++/java.

Overloading in Magic methods

In PHP, there are many magic methods that are used for overloading the following

Property overloading
Method function
__set When an assignment is not an accessible property
__get When reading an inaccessible property
__isset When calling Isset () or empty () on an inaccessible property
__unset When Unset () is called on an inaccessible property

such as: (code from official documents)

classPropertyTest {/** The overloaded data is stored here * /    Private $data=Array();      /** overloads cannot be used on properties that have already been defined * /     Public $declared=1;     /** The overload occurs only when this property is accessed from outside the class * /    Private $hidden=2;     Public function __set($name, $value){Echo "Setting '$name' to '$value'\ n";        $this->data[$name]=$value;} Public function __get($name){Echo "Getting '$name'\ n";        if (array_key_exists($name, $this->data)){return $this->data[$name];}$trace=Debug_backtrace();        Trigger_error(            ' Undefined property via __get (): '.$name.' in '.$trace[0][' file '].' on line '.$trace[0][' line '],            E_user_notice);        return NULL;}/** PHP 5.1.0 after version * /     Public function __isset($name){Echo " is"$name' set?\ n";        return isset($this->data[$name]);}/** PHP 5.1.0 after version * /     Public function __unset($name){Echo "Unsetting '$name'\ n";        unset($this->data[$name]);}/** Non-Magic method * /     Public functionGethidden(){return $this->hidden;}}Echo "<pre>\ n";$obj=NewPropertyTest;$obj->a =1;Echo $obj->a."\ n";Var_dump(isset($obj->a));unset($obj->a);Var_dump(isset($obj->a));Echo "\ n";Echo $obj->declared."\ n";Echo "Let's experiment with the private property named ' Hidden ':\ n";Echo "Privates is visible inside the class, so __get () is not used ...\ n";Echo $obj->gethidden()."\ n";Echo "Privates not visible outside of class, so __get () is used ...\ n";Echo $obj->hidden."\ n";?>

Above output


Setting ' A ' to ' 1 '
Getting ' a '
1

Is ' a ' set?
BOOL (TRUE)
Unsetting ' a '
Is ' a ' set?
BOOL (FALSE)

1

Let's experiment with the private property named ' Hidden ':
Privates is visible inside the class, so __get () is not used ...
2
Privates not visible outside of class, so __get () is used ...
Getting ' hidden '

Notice:undefined property via __get (): Hidden in on line 29


Note that this property is overloaded only if it does not exist.

Method overloading
Method function
__call When a non-accessible method is called in an object
__callstatic When a static class calls a non-accessible method

Example: (Modification from official document code)

<?phpclassmethodtest { Public function __call($name, $arguments){//Note: $name values are case sensitive        Echo "Calling object Method"$name' ".implode(', ', $arguments)."\ n";}/** PHP 5.3.0 after version * /     Public Static function__callstatic($name, $arguments){//Note: $name values are case sensitive        Echo "Calling static method"$name' ".implode(', ', $arguments)."\ n";} Public functionSay(){Echo "Hello\ n";}}$obj=NewMethodtest;$obj->runtest(' in object context ');Methodtest::runtest(' in static context ');  //PHP 5.3.0 later version?>

Output

Calling object method ' Runtest ' in object context
Calling static method ' Runtest ' in static context

Note that when a class method is present, the static call does not call __callstatic, as the call MethodTest::say(); will error

Strict Standards:non-static Method Methodtest::say () should not be called statically

The facade in Laravel

In Laravel, the facade mode can be used to invoke the corresponding business class directly and conveniently using static methods. In fact, facade is taking advantage of the __callstatic feature.
Let us achieve a facade ourselves.
1, Facade parent class, mainly __callstatic overloaded

Abstract classfacade{ Public Static functionGetInstance(){ die("Child class should implement GetInstance");} Public Static function__callstatic($name, $arguments){$instance=Static:: getinstance();        if(!$instance){ die("Instance not init");}if(method_exists($instance,$name)){$instance-$name(...$arguments);//or Call_user_func_array ([$instance, $name], $arguments);}Else{Echo the function$nameis not exist ";}    }}

2, business class, concrete implementation, here we simply output a word

class DemoService {    publicfunction hello($name)    {        echo"hello $name\n";    }}

3, call the façade, inherit facade parent class, implement getinstance can

classextends Facade{    publicstaticfunction getInstance()    {        returnnew DemoService();    }}

4, test Demo::hello("world"); , output

Hello World

Of course, in the Laravel a little more complex, through the container to dynamically obtain instances of the business class.

 Public Static functionGetfacaderoot(){return Static:: Resolvefacadeinstance(Static:: Getfacadeaccessor());}protected Static functionResolvefacadeinstance($name){if (Is_object($name)){return $name;}if (isset(Static::$resolvedInstance[$name])){return Static::$resolvedInstance[$name];}return Static::$resolvedInstance[$name]=Static::$app[$name];}

This $app is when the framework is started by Facade::setFacadeApplication($app); assigning values, which are actually containers.

Extension talk about __invoke

Another interesting method of magic is __invoke, which is called function object in C + +.

Example:

class Add{    publicfunction __invoke($a,$b)    {       return$a+$b;    }}$addnew Add();echo$add(1,3);

What's the use of function objects? In C + + is mainly used to implement the algorithm library STL, in fact, in PHP can also do so.

PHP Reload and laravel façade facade

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.