Abstract Classes in PHP

Abstract classes are those classes which can not be directly initialised. Or in other word we can say that you can not create object of abstract classes. Abstract classes always created for inheritance purpose. You can only inherit abstract class in your child class. Lots of people say that in abstract class at least your one method should be abstract. Abstract method are the method which is only defined but declared. This is not true definition as per my assumption. But your any class has at least one method abstract than your class is abstract class.

Usually abstract class are also known as base class. We call it base class because abstract class are not the class which is available directly for creating object. It can only act as parent class of any normal class. You can use abstract class in class hierarchy. Mean one abstract class can inherit another abstract class also.

Abstract classes in PHP

Abstract classes in php are similar like other oop languages. You can create abstract classes in php using abstract keyword. Once you will make any class abstract in php you can not create object of that class.

above code will throw error in php.

Abstract classes in php are only for inheriting in other class.

In above example you are creating of testChild Class. TestChild class is inheriting testParent abstract class. So your abstract class is only available for inheritance. Main motive of creating abstract classes in php is to apply restriction of direct initialization or object creation.

Implementation of abstract method

As we know that abstract functions are those functions of abstract class which is only defined. It will be declared in your child class. You can create any method abstract using keyword abstract. You can only create abstract method either in abstract class or interface. Following is example of the abstract method implementation:

In class abc we have defined an abstract function f1. Now when we have inherited class abc then declared function f1. If you have an abstract method in your abstract class then once you inherit your abstract class then it is necessary to declare your abstract method. If you will not declare your abstract method then PHP will throw error in that case.

You can declare your abstract method in child class with the same visibility or less restricted visibility.

In above code you can see that you have declare 3 function in abstract class. But private declaration of the abstract method will always throw error. Because private method is available only in the same class context. But in case of f1. This is protected. Now in child class we have defined it as public because public is less restricted than protected. And for function f2 which is already public so we have defined it as public in our child class. We have defined it public because no any visibility is less restricted than public.

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.

Clustered and Secondary Indexes

InnoDB table has a special index called the clustered index where the data for the rows is stored. Typically, the clustered index is synonymous with the primary key. To get the best performance from queries, inserts, and other database operations, you must understand how InnoDB uses the clustered index to optimise the most common lookup and DML operations for each table.

  • When you define a PRIMARY KEY on your table, InnoDB uses it as the clustered index. Define a primary key for each table that you create. If there is no logical unique and non-null column or set of columns, add a new auto-increment column, whose values are filled in automatically.
  • If you do not define a PRIMARY KEY for your table, MySQL locates the first UNIQUE index where all the key columns are NOT NULL and InnoDB uses it as the clustered index.
  • If the table has no PRIMARY KEY or suitable UNIQUE index, InnoDB internally generates a hidden clustered index on a synthetic column containing row ID values. The rows are ordered by the ID that InnoDB assigns to the rows in such a table. The row ID is a 6-byte field that increases monotonically as new rows are inserted. Thus, the rows ordered by the row ID are physically in insertion order.
How the Clustered Index Speeds Up Queries

Accessing a row through the clustered index is fast because the index search leads directly to the page with all the row data. If a table is large, the clustered index architecture often saves a disk I/O operation when compared to storage organisations that store row data using a different page from the index record. (For example, MyISAM uses one file for data rows and another for index records.)

How Secondary Indexes Relate to the Clustered Index

All indexes other than the clustered index are known as secondary indexes. In InnoDB, each record in a secondary index contains the primary key columns for the row, as well as the columns specified for the secondary index. InnoDB uses this primary key value to search for the row in the clustered index.

If the primary key is long, the secondary indexes use more space, so it is advantageous to have a short primary key.

 

MySQL INDEXES

Database index is a data structure that improves the speed of operations in a table. Indexes can be created using one or more columns.

While creating index, it should be considered that what are the columns which will be used to make SQL queries and create one or more indexes on those columns.

Practically, indexes are also type of tables, which keep primary key or index field and a pointer to each record into the actual table.

The users cannot see the indexes, they are just used to speed up queries and will be used by Database Search Engine to locate records very fast.

INSERT and UPDATE statements take more time on tables having indexes where as SELECT statements become fast on those tables. The reason is that while doing insert or update, database need to insert or update index values as well.

Simple and Unique Index:

You can create a unique index on a table. A unique index means that two rows cannot have the same index value. Here is the syntax to create an Index on a table

You can use one or more columns to create an index. For example, we can create an index on authors_tbl using author_name.

You can create a simple index on a table. Just omit UNIQUE keyword from the query to create simple index. Simple index allows duplicate values in a table.

If you want to index the values in a column in descending order, you can add the reserved word DESC after the column name.

ALTER command to add and drop INDEX:

There are four types of statements for adding indexes to a table:

  • ALTER TABLE tbl_name ADD PRIMARY KEY (column_list): This statement adds a PRIMARY KEY, which means that indexed values must be unique and cannot be NULL.
  • ALTER TABLE tbl_name ADD UNIQUE index_name (column_list): This statement creates an index for which values must be unique (with the exception of NULL values, which may appear multiple times).
  • ALTER TABLE tbl_name ADD INDEX index_name (column_list):This adds an ordinary index in which any value may appear more than once.
  • ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list): This creates a special FULLTEXT index that is used for text-searching purposes.

Here is the example to add index in an existing table.

You can drop any INDEX by using DROP clause along with ALTER command. Try out the following example to drop above-created index.

You can drop any INDEX by using DROP clause along with ALTER command. Try out the following example to drop above-created index.

ALTER Command to add and drop PRIMARY KEY:

You can add primary key as well in the same way. But make sure Primary Key works on columns, which are NOT NULL.

Here is the example to add primary key in an existing table. This will make a column NOT NULL first and then add it as a primary key.

You can use ALTER command to drop a primary key as follows:

To drop an index that is not a PRIMARY KEY, you must specify the index name.

Displaying INDEX Information:

You can use SHOW INDEX command to list out all the indexes associated with a table. (wraparound by \G):

Try out the following example: