Container mode from anonymous function (Closure feature) to PHP design mode

Source: Internet
Author: User
Tags closure php language learn php php framework

anonymous function (anonymous function)an anonymous function, also called a closure function, allows you to temporarily create a function that does not have a specified name, commonly used as the value of a callback function parameter, or as the value of a variable. For specific use, see the following sample code:
/*Example One: Declare a simple anonymous function and assign a value to a variable, call this anonymous function by the variable name*/$anonFunc=function($param){        Echo $param;};
$anonFunc(' Here is an anonymous function '); Calling anonymous functions through variable names is no different from normal functions
/*Example two: dynamically creating functions by using anonymous functions inside a function*/functionOperate$operator){ if($operator= = ' + '){ return function($a,$b){ return $a+$b; } } if($operator= = '-'){ return function($a,$b){ return $a-$b; } }}$add= Operate (' + '));Echo $add(4, 3);//7$sub= Operate ('-'));Echo $sub(4, 3);//1?/*Example Three: An anonymous function passed in as a callback function parameter*/function Callback($callback){ $callback();}function Callback(){ //Closure test function Echo' This is the closure test function body ';}
Of the three examples in the code above, anonymous functions are not being passed, and we knowanonymous functions are used very frequently in JavaScript, and parameter variables in the parent function can be used directly in the child functions, but the PHP language does not allow this and requires the use of the using ($var) keyword (note how the code is used) for the same purpose. For example three in the code above, make the following modifications:
/*example Three modifications: An anonymous function is passed in as a parameter and carries parameters*/function Callback($callback) Use($content){    $callback($content);}$content= ' This is the output content of the closure function ';function Callback($content){    //closure function    Echo $content;}
Example two in the code above, you can alsoThe use keyword is used to implement an anonymous function reference to the outer variables of the parent function. The use of anonymous functions and closures in these sample code is only to understand the concept, and there is not much practical meaning, the use of closures is many, common is used in the PHP framework in the container mode of the dependency injection (DI).
PHP Object-oriented container modeAs the name implies, containers are used to store things, in fact, is to declare a class, specifically to access object instances, so, thenThere must be at least two core methods in the container to implement the binding dependency to the container and to get dependencies from the container. A container can be said to be a dependency management tool, sometimes called a service container.
/*declaring a simple container class*/classcontainer{Private $_dilist=Array();//for storing dependencies? /*one of the core methods used to bind the service * @param string $className class name * @param mixed $concrete depends on how it is stored in the container, can be a class name string, an array, an instantiated object, or an anonymous function */PuclicfunctionSet$className,$concrete){? $this->_dilist[$className] =$concrete;    }? /** Two of the core methods, used to get the service object * @param string $className The name of the dependency to be obtained * @return object returns a dependent instantiation object*/     Public functionGet$className){        if(isset($this->_dilist[$className])){            return $this->dilist[$className]; }            return NULL; }}
The above code is a simple container pattern in which the set method is used to register dependencies, and the Get method is used to obtain dependencies.container storage relies on a lot of ways (referring to the note, "Dependency Injection (DI) and control inversion (IOC) of the PHP object-oriented container pattern"), the following sample code is described in the form of an anonymous function.
/*Database Connection Classes*/classconnection{ Public function__construct ($dbParams){        //connect the database ...    }     PublicSomedbtask () {//code ...    }}/*Session Control Classes*/classsession{ Public functionopensession () {Session_Start(); }    //code ...}$container->set (' Session ',function(){    return NewSession ();});?$container=NewContainer ();//Registering a database connection service with a container$container->set (' db ',function(){    return NewConnetion (Array(          "Host" = "localhost", "username" = "root", "password" and "root", "dbname" and "DBN" Ame      ));});//Registering a Session Control service with a container$container->set (' Session ',function(){    return NewSession ();});//get the services that were previously registered with the container and do business processing$container->get (' db ')Somedbtask ();$container->get (' Session ')->opensession ();

The above code is the use of the container, which registered the DB and session two services, where the anonymous function as a dependent storage, in the call $container->set () method to register the service is not actually instantiated, but in the call $ When the Container->get () method obtains the dependency, it executes the anonymous function and returns the instantiated object, which realizes the on-demand instantiation, without the instantiation, and improves the running efficiency of the program.

Reference article Source:1.Http://www.thinkphp.cn/topic/13624.html
2.https://www.cnblogs.com/sweng/p/6430374.html3.http://www.jb51.net/article/114723.htm
4.http://blog.csdn.net/realghost/article/details/35212285
5.The " PHP anonymous functions and Closures" chapter and related notes in the book "Connect with Brothers and learn PHP"

Container mode from anonymous function (Closure feature) to PHP design mode

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.