Interface in PHP

Interface

Interface in oop enforce definition of some set of method in the class. By implementing interface you are forcing any class to must declaring some specific set of methods in oop. For example if you are creating class to render HTML element then it is necessary to set id and name of your html tag. So in this case you will create interface for that class and define method like setID and setName. So whenever someone will create any class to render HTML tag and implemented your interface then he must need to define setId and setName method in their class. In other word you can say that by help of interface you can set some definition of your object. Interface is very useful if you are creating architecture of any oop base application.

Interface in PHP

Interface in php can be implemented like other oop lanugage. You can create interface in php using keyword interface. By implementation of interface in php class you are specifying set of the method which classes must implement.

You can create interface in php using interface keyword. Rest of the things are typically identical to classes. Following is very small example of interface in php.

So in above code you are creating interface with name abc. Interface abc has function xyz. Whenever you will implement abc interface in your class then you have to create method with name xyz. If you will not create function xyz then it will throw error.

You can implement your interface in your class using implements keyword. Let us implement our interface abc in our class

You can only define method in interface with public accessibility. If you will use other than public visibility in interface then it will throw error. Also while defining method in your interface do not use abstract keyword in your methods.

You can also extend interface like class. You can extend interface in php using extends keyword.

So here template2 has all property of tempate2. So whenever you will implement template2 in your class, you have to create function of both interfaces.

You can also extend multiple interface in one interface in php.

You can also implement more than one interface in php class.

You can not implement 2 interfaces if both share function with same name. It will throw error.

Your function parameter in class must be identical to the parameter in the interface signature. Following is example some example

Above will work. But following example will not work:

But it is not necessary to use the same name of the variable. Like $a. You can also use any name. For example:

If  you are using default argument then you can change your value of the argument. For example

 

PHP cURL

cURL

cURL stand for Client URL. cURL is a library to transfer data via various protocol like http, ftp, tftp etc. By using cURL we can send HTTP request using various method like GET, POST etc. First cURL library was released in 1997. cURL project was originally started by Daniel Stenberg. cURL project has 2 part, cURL command line tool and libcurl library. Command line tool is generally available in Linux distributions for transferring data on various protocol like HTTP, HTTPS, FTP etc. Libcurl is library which support data transfer on different protocol.

Libcurl is available with various language including PHP. For more information about the cURL project you can visit cURL or cURL page.

All cURL feature in PHP is available through libcurl. In the series of PHP cURL we will explore around the various aspect of libcurl in php.

Below are the general thing which we can do using php curl library

  1. Downloading HTML from URL in our PHP Code.
  2. Sending POST request on any URL. 
  3. Calling Rest full API.

cURL support in php is introduced from php version 4.0.2

Install cURL Library in PHP

PHP has extension which need to be installed and enable to use cURL features. But to use the php cURL functionality you need to install libcurl package on your system/server. Most of the Linux system come with the by default installation of libcurl. Also if you are going to use PHP using XAMPP or WAMPP then also you no need to think about the libcurl package installation.

To check whether curl is enable or not you can use phpinfo() command. If your phpinfo page has below section appeared then curl is enable with your PHP.

php-curl

If above section is not available then you need to enable curl. Below are the steps to enable curl extension in php

  • If you are using WAMPP or XAMPP then open your php.ini file and uncomment below line
    ;extension=php_curl.dll
  • If you have manually installed PHP then you can install php_curl library and then add below line in your php.ini
    extension=php_curl.dll
  • If you are using php by compiling the source code then please compile with parameter –with-curl.

Hope we are all set to go. Let us see some magic with php curl:

PHP Curl Example

Below is a very basic code written using libcurl.

Above code is fetching homepage of url http://www.google.co.in .  Below thing we are doing in above code.

  1. Initialising curl.
  2. Setting option URL to google.com.
  3.  Setting option to transfer data as string.
  4. Executing Curl and taking output string in a variable.
  5. Closing the curl handle.
  6. printing result.

In above code we have used some methods like curl_init , curl_setopt, curl_close which are function available with curl library of php.

cURL Function

PHP cUrl library provides 29 function. You can get full list of php curl function here. Let us look at some of imporent cURL function:

  1. curl_init
  2. curl_setopt & curl_setopt_array
  3. curl_exec
  4. curl_getinfo
  5. curl_close
  6. curl_error
  7. curl_errorno

1) curl_init : curl_init function is used to initialise  the new session. curl_init returns a cURL handle. Curl handle is passed in various other curl method call like setting option, executing the curl session etc.  Curl_init function has a optional URL parameter.  Below is the example of curl_init:

Below is example of initialising the curl with URL

Above code is equivalent to below

2) curl_setopt and set_opt_array : Both method are used to set option like http header, timeout  with your curl session. In curl_setopt need to pass options one by one however in curl_setopt_array option more than one option can be passed simultaneously. Both curl_setopt and curl_setopt_array need curl session to be initialised.

Here you can get complete list of option available with php curl library.

3) curl_exec : Curl_exec function is to execute the curl session. Returns true if session is executed succesffully otherwise false. But if you will set option CURL_RETURNTRANSFER true then it will return output of the curl session.

4) curl_getinfo : Method will return detail information about curl transfer session. For example:

Above code will return below detail output regarding this session:

5) curl_close : Function used to close curl transfer session. Function require curl handle as input parameter.

6) curl_error : Function return last error of the curl_session. If error will not occur then it will return empty string.

7) Curl_errorno : Function return last error number of curl_session.

PHP Cache

If your website receives a good amount of traffic everyday and your webpages are loading slow, you might want to consider implementing some sort of caching mechanism on your website to speed-up page loading time. Because as we all know that each client-server request consists of many queries, loops, calculations, database queries etc. these all add-up to processing time, which eventually increases page loading time. The most simplest way to avoid all these is to create cache files and store them in a separate directory, which can later be served as fast loading static pages instead of regular dynamic pages.

PHP Caching

There are several other PHP cache engines such as APC, Xcache or OPcache to boost your application performance, but they all work quite differently, to understand them you can find many tutorials dedicated to them on the web. Here I’m going to show you the most simplest way of caching PHP pages, and that is using PHP Output Buffer and Filesystem Functions, combining these two methods we can have magnificent caching system.

PHP Output buffer :— It interestingly improves performance and decreases the amount of time it takes to download, because the output is not being sent to browser in pieces but the whole HTML page as one variable. The method is insanely simple take a look at the code below :


When you call ob_start() on the top of the code, it turns output buffering on, which means anything after this will be stored in the buffer, instead of outputting on the browser. The content in the buffer can be retrieved using ob_get_contents(). You should call ob_end_flush() at the end of the code to send the output to the browser and turn buffering off.

PHP Filesystem :— You may be familiar with PHP file system, it is a part of the PHP core, which allow us to read and write the file system. Have a look at the following code.


As you can see the first line of the code fopen() opens the file for writing, the mode ‘w’ places the file pointer at the beginning of the file and if file does not exist, it attempts to create one. Second line fwrite() writes the string to the opened file, and finally fclose() closes the successfully opened file at the beginning of the code.

Implementing PHP caching

Now you should be pretty clear about PHP output buffer and filesystem, we can use these both methods to create our PHP caching system. Please have a look at the picture below, the Flowchart gives us the basic idea about our cache system.

php-cache-system

The cycle starts when a user request the content, we just check whether the cache copy exist for the currently requested page, if it doesn’t exist we generate a new page, create cache copy and then output the result. If the cache already exist, we just have to fetch the file and send it to the user browser.

Take a look at the Full PHP cache code below, you can just copy and paste it in your PHP projects, it should work flawlessly as depicted in above Flowchart. You can play with the settings in the code, modify the cache expire time, cache file extension, ignored pages etc.


Read the comment lines in the code carefully, you should find it pretty much self explanatory.

  1. Get the currently requested URL location.
  2. Construct a location path for the cache file, convert URL to MD5 hash for the fixed cache file name.
  3. Check whether URL is in ignore list.
  4. Check for existing unexpired cache file, if exist, just open and output the content with gzip compression.
  5. Or else, we create a new cache file and output the HTML result with gzip compression.

Design Patterns in PHP

There are number of ways to structure your code and project for your applications. Use of design patterns is usually a good idea to follow common patterns because it will make your code easier to manage and easier for others to understand.

We have five deigns patterns these are:

  • Factory
  • Singleton
  • Strategy
  • Front Controller
  • Model-View Controller

Factory

Factory pattern is most commonly used design patterns. In this pattern, a class simply creates the object you want to use. Consider the following example of the factory pattern:

This code uses a factory to create the Vehicle object. There are two possible benefits to building your code this way; the first is that if you need to change, rename, or replace the Vehicle class later on you can do so and you will only have to modify the code in the factory, instead of every place in your project that uses the Automobile class. The second possible benefit is that if creating the object is a complicated job you can do all of the work in the factory, instead of repeating it every time you want to create a new instance.

Using the factory pattern isn’t always necessary (or wise). The example code used here is so simple that a factory would simply be adding unneeded complexity. However if you are making a fairly large or complex project you may save yourself a lot of trouble down the road by using factories.

Singleton

When designing web applications, it often makes sense conceptually and architecturally to allow access to one and only one instance of a particular class. The singleton pattern enables us to do this.

The code above implements the singleton pattern using a static variable and the static creation method getInstance(). Note the following:

  • The constructor __construct() is declared as protected to prevent creating a new instance outside of the class via the new operator.
  • The magic method __clone() is declared as private to prevent cloning of an instance of the class via the clone operator.
  • The magic method __wakeup() is declared as private to prevent unserializing of an instance of the class via the global function unserialize() .
  • A new instance is created via late static binding in the static creation method getInstance() with the keyword static. This allows the subclassing of the class Singleton in the example.

The singleton pattern is useful when we need to make sure we only have a single instance of a class for the entire request lifecycle in a web application. This typically occurs when we have global objects (such as a Configuration class) or a shared resource (such as an event queue).

You should be wary when using the singleton pattern, as by its very nature it introduces global state into your application, reducing testability. In most cases, dependency injection can (and should) be used in place of a singleton class. Using dependency injection means that we do not introduce unnecessary coupling into the design of our application, as the object using the shared or global resource requires no knowledge of a concretely defined class.

 

Strategy

With the strategy pattern you encapsulate specific families of algorithms allowing the client class responsible for instantiating a particular algorithm to have no knowledge of the actual implementation. There are several variations on the strategy pattern, the simplest of which is outlined below:

This first code snippet outlines a family of algorithms; you may want a serialized array, some JSON or maybe just an array of data:

By encapsulating the above algorithms you are making it nice and clear in your code that other developers can easily add new output types without affecting the client code.

You will see how each concrete ‘output’ class implements an OutputInterface – this serves two purposes, primarily it provides a simple contract which must be obeyed by any new concrete implementations. Secondly by implementing a common interface you will see in the next section that you can now utilise Type Hinting to ensure that the client which is utilising these behaviours is of the correct type in this case ‘OutputInterface’.

The next snippet of code outlines how a calling client class might use one of these algorithms and even better set the behaviour required at runtime:

The calling client class above has a private property which must be set at runtime and be of type ‘OutputInterface’ once this property is set a call to loadOutput() will call the load() method in the concrete class of the output type that has been set.

 

Front Controller

The front controller pattern is where you have a single entrance point for your web application (e.g. index.php) that handles all of the requests. This code is responsible for loading all of the dependencies, processing the request and sending the response to the browser. The front controller pattern can be beneficial because it encourages modular code and gives you a central place to hook in code that should be run for every request (such as input sanitization).

Model-View-Controller

The model-view-controller (MVC) pattern break up code into logical objects that serve very specific purposes. Models serve as a data access layer where data is fetched and returned in formats usable throughout your application. Controllers handle the request, process the data returned from models and load views to send in the response, and views are display templates (markup, xml, etc) that are sent in the response to the web browser.

MVC is the most common architectural pattern used in the popular frameworks.

Helpful Links: