PHP implements the registration tree mode

Source: Internet
Author: User
Tags instance method

Register Tree mode (Registry pattern): The registration tree mode creates a central memory for objects that are used frequently in the application-usually through an abstract class that contains only static methods (or through singleton mode). Also known as the Registrar mode

(a) Why registration of tree mode is required
解决常用对象的存放问题,实现类似于全局变量的功能。
(ii) registration tree mode UML diagram

Not currently

(c) Simple examples
<?phpThe user class is used for testingClassuser{}Registering Tree ClassesClassregistry{ProtectedStatic $objects;For storing instancesDeposit instance MethodStaticPublicfunctionSet($key, $object) {Self:: $objects [$key] = $object; }Get instance methodStaticPublicfunctionGet($key) {if (!IssetSelf:: $objects [$key]) {ReturnFALSE;} return self:: $objects [$key];} //Delete instance method static public function _unset  ($key) {unset (self:: $objects [$ Key]); }} $user = new user; Deposit Instance Registry::set ( ' User ', $user);  Delete Instance Registry::_unset ( "User");        

The registration tree is often used in conjunction with Singleton mode, first to see if there is an instance on the registration tree, to use it directly, to generate an instance, and to hang it on the tree. Sometimes we can also do this, let get method if get not to the instance of the time when the new one is stored, so that we use no tube has stored this instance, anyway, the Get method will also help us to store.

  //获取实例方法    static public function get($key) { if (!isset(self::$objects[$key])) { self::$objects[$key] = new $key; } return self::$objects[$key]; }

Of course, if you use this method, you can't use the Get method if you see if the instance exists. An instance is generated because the Get method is called after it does not exist.

PHP implements the registration tree 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.