Modern PHP new features series (ii)--use interface

Source: Internet
Author: User
Interface is not a new feature of modern PHP, but it is very important to learn to use the interface, can greatly improve our programming ability, so in daily development should use as much as possible interface.

The interface is a contract between two PHP objects (contract), and the laravel is placed directly in the contracts directory:

The interface decouples our code and dependencies, and allows our code to rely on any third-party code that implements the intended interface, regardless of how the third-party code implements the interface, and whether the third-party code implements the specified interface.

If the code we write needs to handle the object of the specified class, then the function of the code is fully qualified, because the object of that class is always used, but if the code is written to handle an interface, the code immediately knows how to handle any object that implements the interface, and we don't care how the interface is implemented. Only cares if the specified interface is implemented.

As an example of the Cachestore (store interface) provided by the above-mentioned laravel, this interface serves as a common method for encapsulating cache memory, including get, put, flush, and so on:

     

The advantage of this is that you can define specific cache implementations separately, such as Laravel support Arrays (array), database, file, Apc, Memcache, Redis, and other cache memories. It is convenient for us to cache the data in the appropriate way in the code. We take the memcached drive as an example, and its corresponding implementation class is Memcachedstore:

  Setprefix ($prefix);    $this->memcached = $memcached;     }/** * Retrieve an item from the cache by key. * * @param string|array $key * @return Mixed */Public function get ($key) {$value = $this        Memcached->get ($this->prefix. $key);        if ($this->memcached->getresultcode () = = 0) {return $value;     }}/** * Retrieve multiple items from the cache by key.     * Items not found in the cache would have a null value. * * @param array $keys * @return Array */Public function many (array $keys) {$prefixedKeys = a        Rray_map (function ($key) {return $this->prefix. $key;        }, $keys);        $values = $this->memcached->getmulti ($prefixedKeys, NULL, memcached::get_preserve_order);        if ($this->memcached->getresultcode ()! = 0) {return Array_fill_keys ($keys, NULL);    } return Array_combine ($keys, $values);  }    /**   * Store an item in the cache for a given number of minutes. * * @param string $key * @param mixed $value * @param int $minutes * @return void */Publ IC function put ($key, $value, $minutes) {$this->memcached->set ($this->prefix. $key, $value, $minutes *    60);     }/** * Store multiple items in the cache for a given number of minutes. * * @param array $values * @param int $minutes * @return void */Public Function Putmany (array $val        UEs, $minutes) {$prefixedValues = [];        foreach ($values as $key = + $value) {$prefixedValues [$this->prefix. $key] = $value;    } $this->memcached->setmulti ($prefixedValues, $minutes * 60);     }/** * Store a item in the cache if the key doesn ' t exist. * * @param string $key * @param mixed $value * @param int $minutes * @return bool */Publ IC function Add ($key, $value, $minutes)   {return $this->memcached->add ($this->prefix. $key, $value, $minutes * 60);     }/** * Increment The value of a item in the cache.  * * @param string $key * @param mixed $value * @return Int|bool */Public Function increment ($key,    $value = 1) {return $this->memcached->increment ($this->prefix. $key, $value);     }/** * Decrement the value of a item in the cache.  * * @param string $key * @param mixed $value * @return Int|bool */Public Function decrement ($key,    $value = 1) {return $this->memcached->decrement ($this->prefix. $key, $value);     }/** * Store an item in the cache indefinitely. * * @param string $key * @param mixed $value * @return void */Public Function Forever ($key, $valu    e) {$this->put ($key, $value, 0);     }/** * Remove an item from the cache. * * @param string $key * @return bool     */Public Function Forget ($key) {return $this->memcached->delete ($this->prefix. $key);     }/** * Remove all items from the cache.    * * @return void */Public Function flush () {$this->memcached->flush ();     }/** * Get the underlying Memcached connection.    * * @return \memcached */Public Function getmemcached () {return $this->memcached;     }/** * Get the cache key prefix.    * * @return String */Public Function Getprefix () {return $this->prefix;     }/** * Set the cache key prefix. * * @param string $prefix * @return void */Public Function Setprefix ($prefix) {$this->pref IX =! Empty ($prefix)?    $prefix. ': ': '; }}

We can see that we passed the memcached instance in the constructor, and then we implement the method defined by the interface on the basis of this instance, and the other implementation classes are similar, so that through the store interface, we decouple the cached code from the specific dependencies, so that it is easy to expand and use for other people. For example, here we define a Cachestore class:

 
   store = $store;    }    Public function Get ($key)    {        return $this->store->get ($key);    }    Public function put ($key, $value, $minutes =1)      {        $this->store->put ($key, $value, $minutes);    }    Public function Forget ($key)    {        $this->store->forever ($key);    }    Public Function Flush ()    {        $this->store->flush ();    }}

Then we can configure the default cache driver used in the configuration file, such as memcached, and then use it when called in the code:

$memcached = new \memcached (); $memcached->addserver (' localhost ', 11211); $memcachedCache = new Memcachedstore ($ memcached); $cacheStore = new Cachestore ($memcachedCache); $cacheStore->put (' site ', ' http://LaravelAcademy.org '); DD ($cacheStore->get (' site '));

Note: Here is just a simple demonstration, do not really use the laravel provided by the caching function, in fact, laravel the underlying cache processing is more elegant than my demo code here.

In short, the code written with the interface is more flexible, can delegate others to implement the details, using the interface will be more and more people use your code, because they just need to know how to implement the interface, you can seamlessly use your code. In fact, we use service providers and dependency injection as a more complex extension based on this interface-oriented programming.

  • 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.