Sunday, September 21, 2014

Abstract Classes and Interface in PHP

Abstract class and Interface in php play very important role in oop. In this section we will discuss following point
  1. What is abstract classes.
  2. What is interface
  3. How to implement abstract classes in php
  4. How to implement interface in php
  5. Different between abstract classes and interface.

What is abstract Classes

As from name it seem like something that is hidden. Yes nature of the abstract classes are same. Abstract classes are those classes which can not be directly initialized. 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 simillar like other oop languages. You can create abstract classes in php using abstractkeyword. Once you will make any class abstract in php you can not create object of that class.
abstract class abc
{
public function xyz()
{
return 1;
}
}
$a = new abc();//this will throw error in php

above code will throw error in php.
Abstract classes in php are only for inheriting in other class.
abstract class testParent
{
public function abc()
{
//body of your funciton
}
}
class testChild extends testParent
{
public function xyz()
{
//body of your function
}
}
$a = new testChild();

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:
abstract class abc
{
abstract protected function f1($a , $b);
}
class xyz extends abc
{
protected function f1($name , $address)
{
echo "$name , $address";
}
}
$a = new xyz();
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.
abstract class parentTest
{
abstract protected function f1();
abstract public function f2();
//abstract private function f3(); //this will trhow error
}
class childTest
{
public function f1()
{
//body of your function
}
public function f2()
{
//body of your function
}
protected function f3()
{
//body of your function
}
}
$a = new childTest();
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 availabe 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.

What is 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. Inter

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.
interface abc
{
public function xyz($b);
}

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
class test implements abc
{
public function xyz($b)
{
//your function body
}
}
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.
interface template1
{
public function f1();
}
interface template2 extends template1
{
public function f2();
}
class abc implements template2
{
public function f1()
{
//Your function body
}
public function f2()
{
//your function body
}
}

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.
interface template1
{
public function f1();
}
interface template2
{
public function f2();
}
interface template3 extends template1, template2
{
public function f3();
}
class test implements template3
{
public function f1()
{
//your function body
}
public function f2()
{
//your function body
}
public function f3()
{
//your function body
}
}
You can also implement more than one interface in php class.
interface template1
{
public function f1();
}
interface template2
{
public function f2();
}
class test implments template1, template2
{
public function f1()
{
//your function body
}
public function f2()
{
//your function body
}
}

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
interface template1
{
public function f1($a)
}
class test implements template1
{
public function f1($a)
{
echo $a;
}
}

Above will work. But following example will not work:
interface template1
{
public function f1($a)
}
class test implements template1
{
public function f1()
{
echo $a;
}
}

But it is not necessary to use the same name of the variable. Like $a. You can also use any name. For example:
interface template1
{
public function f1($a)
}
class test implements template1
{
public function f1($name)
{
echo $name;
}
}

If you are using default argument then you can change your value of the argument. For example
interface template1
{
public function f1($a = 20)
}
class test implements template1
{
public function f1($name  = "ankur")
{
echo $name;
}
}
In above section we have discussed interfaces and abstract classes in php. Both are almost doing same things but has some difference.

Differences between abstract class and interface in PHP

Following are some main difference between abstract classes and interface in php
  1. In abstract classes this is not necessary that every method should be abstract. But in interface every method is abstract.
  2. Multiple and multilevel both type of inheritance is possible in interface. But single and multilevel inheritance is possible in abstract classes.
  3. Method of php interface must be public only. Method in abstract class in php could be public or protected both.
  4. In abstract class you can define as well as declare methods. But in interface you can only defined your methods.

Tuesday, June 17, 2014

Dreamweaver Keyboard Shortcuts

Alt + Backspace Undo

Alt + F4 Exit/Quit

Alt + F8 View Site Map

Alt + F9 Display Timeline

Alt + F11 Live View

Alt F6 - Expanded Tables Mode

Control + ' Balance Braces
Control+` Switch between Design and Code Views

Control + - Zoom Out

Control + . Refresh Code Hints

Control + ;
 Show Guides

Control + [ Select Parent Tag

Control + ] Select Child

Control + = Zoom In

Control + 0 Remove Paragraph Tags

Control + 1 Paragraph Format H1

Control + 2 Paragraph Format H2

Control + 3 Paragraph Format H3

Control + 4 Paragraph Format H4

Control + 5 Paragraph Format H5

Control + 6 Paragraph Format H6

Control + A Select All

Control + Alt + ; Lock Guides

Control + Alt + [ Outdent

Control + Alt + ] Indent

Control + Alt + 0
 Fit Selection

Control + Alt + 1 Zoom 100%

Control + Alt + 2 Zoom 200% 

Control + Alt + 3 Zoom 300%

Control + Alt + 4 Zoom 400% 

Control + Alt + 5 Zoom 50% 

Control + Alt + 6 Zoom 1600%

Control + Alt + 8 Zoom 800%

Control + Alt + A Insert Named Anchor

Control + Alt + C Collapse Outside Selection

Control + Alt + E Expand All

Control + Alt + F12 Open Device Central

Control + Alt + G
 Show Grid 

Control + Alt + I Insert Image

Control + Alt + J Collapse Outside Full Tag

Control + Alt + M Table Formatting - Merge Cells

Control + Alt + O Browse in Bridge

Control + Alt + P Play Plugin 

Control + Alt + R 
Show All Rulers

Control + Alt + S Table Formatting - Split Cell

Control + Alt + Shift + 0 Fit Width

Control + Alt + Shift + C Align Center

Control + Alt + Shift + D Check Out

Control + Alt + Shift + G Snap to Grid

Control + Alt + Shift + J Align Justify

Control + Alt + Shift + L Align Left

Control + Alt + Shift + P
 Play All Plugins 

Control + Alt + Shift + R Align Right

Control + Alt + Shift + U 
Check In

Control + Alt + Shift + X Stop All Plugins

Control + Alt + V
 Insert Editable Region

Control + Alt + X Stop Plugin

Control + B Bold

Control + C Copy

Control + E Insert Tag

Control + F Find and Replace

Control + F10 
Bindings

Control + F1 ColdFusion Help 

Control + F2 Insert

Control + F3 Properties

Control + F7 Components

Control + F8 Check Links Site Wide

Control + F9 Server Behaviours

Control + G Go to line

Control + I Italic

Control + J Modify Page Properties

Control + L Make Link

Control + M Table Formatting - Insert Row

Control + N New file

Control + P Print Code

Control + S Save

Control + Shift + - Table Formatting - Delete Column

Control + Shift + / Guides Snap to Elements

Control + Shift + ; Snap to Guides

Control + Shift + [ 
Table Formatting - Decrease Column Span

Control + Shift + ] Table Formatting - Increase Column Span

Control + Shift + < Outdent Code

Control + Shift + > Indent Code

Control + Shift + 0 
Fit All

Control + Shift + 0 
Open in Frame

Control + Shift + 1
Table Formatting - Align Left

Control + Shift + 3
 Table Formatting - Align Right

Control + Shift + 4 Table Formatting - Align Top 

Control + Shift + 6 Table Formatting - Align Bottom

Control + Shift + 7 Table Formatting - Make Same Width

Control + Shift + 9 
Table Formatting - Make Same Height

Control + Shift + A Table Formatting - Insert Column

Control + Shift + C 
Collapse Selection

Control + Shift + D Get

Control + Shift + E Expand Selection

Control + Shift + F10 Databases

Control + Shift + H Head Content

Control + Shift + I
 Hide All Visual Aids

Control + Shift + J Collapse Full Tag

Control + Shift + L Remove Link

Control + Shift + M Table Formatting - Delete Row

Control + Shift + P Normal Paragraph Format

Control + Shift + S Save As

Control + Shift + Space 
Insert Non-Breaking Space

Control + Shift + U
 Put

Control + Shift + V Paste Special

Control + Shift + W 
Close All

Control + Shift + X 
Start Recording

Control + Spacebar Show Code Hints

Control + T Quick Tag Editor

Control + V
 Paste

Control + W Close

Control + X Cut 

Control + Y 
Redo

Control + Z
 Undo

Control +Alt + T Insert Table

Control Q Exit

Control+ O 
Open file

F1 Dreamweaver Help

F10 Code Inspector

F12 Preview in browser

F2 AP Elements

F3 Find Next

F4 Hide Panels

F5 Refresh Design View

F6 Whilst in Live View - Freeze Javascript

F7 Search

F8 Files

Shift + Enter Insert Line Break

Shift + F1 Reference

Shift + F10 History

Shift + F11 CSS Styles

Shift + F2 Frames

Shift + F3 Find Selection

Shift + F4
 Behaviours

Shift + F7 
Check Spelling

Shift + F8 Check Page Links

Shift + F9 Tag Inspector

Shift F6 Validate Markup

Tuesday, May 27, 2014

Using CURL for Remote Requests

If you’re a Linux user then you’ve probably used cURL. It’s a powerful tool used from posting mails to downloading the latest My Little Pony subtitles. In this article I’ll explain how to use the cURL extension in PHP. The extension offers us the functionality as the console utility in the comfortable world of PHP. I’ll discuss sending GET and POST requests, handling login cookies, and FTP functionality.
Before we begin, make sure you have the extension (and the libcURL library) installed. It’s not installed by default. In most cases it can be installed using your system’s package manager, but barring that you can find instructions in the PHP manual.
How Does it Work?
All cURL requests follow the same basic pattern:
1.      First we initialize the cURL resource (often abbreviated as ch for “cURL handle”) by calling the curl_init()function.
2.      Next we set various options, such as the URL, request method, payload data, etc. Options can be set individually with curl_setopt(), or we can pass an array of options to curl_setopt_array().
3.      Then we execute the request by calling curl_exec().
4.      Finally, we free the resource to clear out memory.
So, the boilerplate code for making a request looks something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
// init the resource
$ch = curl_init();

// set a single option...
curl_setopt($ch, OPTION, $value);
// ... or an array of options
curl_setopt_array($ch, array(
    OPTION1 => $value1,
    OPTION2 => $value2
));

// execute
$output = curl_exec($ch);

// free
curl_close($ch);
The only thing that changes for the request is what options are set, which of course depends on what you’re doing with cURL.
Retrieve a Web Page
The most basic example of using cURL that I can think of is simply fetching the contents of a web page. So, let’s fetch the homepage of the BBC as an example.
1
2
3
4
5
6
7
8
9
<?php
curl_setopt_array(
    $ch, array(
    CURLOPT_URL => 'http://www.bbc.co.uk/',
    CURLOPT_RETURNTRANSFER => true
));

$output = curl_exec($ch);
echo $output;
Check the output in your browser and you should see the BBC website displayed. We’re lucky as the site displays correctly because of its absolute linking to stylesheets and images.
The options we just used were:
·         CURLOPT_URL – specifies the URL for the request
·         CURLOPT_RETURNTRANSFER – when set false, curl_exec() returns true or false depending on the success of the request. When set to true, curl_exec() returns the contents of the response.
Log in to a Website
cURL executed a GET request to retrieve the BBC page, but cURL can also use other methods, such as POST and PUT. For this example, let’s simulate logging into a WordPress-powered website. Logging in is done by sending a POST request to http://example.com/wp-login.php with the following details:
·         login – the username
·         pwd – the password
·         redirect_to – the URL we want to go to after logging in
·         testcookie – should be set to 1 (this is just for WordPress)
Of course these parameters are specific to each site. You should always check the input names for yourself, something that can easily be done by viewing the source of an HTML page in your browser.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
$postData = array(
    'login' => 'acogneau',
    'pwd' => 'secretpassword',
    'redirect_to' => 'http://example.com',
    'testcookie' => '1'
);

curl_setopt_array($ch, array(
    CURLOPT_URL => 'http://example.com/wp-login.php',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $postData,
    CURLOPT_FOLLOWLOCATION => true
));

$output = curl_exec($ch);
echo $output;
The new options are:
·         CURLOPT_POST – set this true if you want to send a POST request
·         CURLOPT_POSTFIELDS – the data that will be sent in the body of the request
·         CURLOPT_FOLLOWLOCATION – if set true, cURL will follow redirects
Uh oh! If you test the above however you’ll see an error message: “ERROR: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress.” This is normal, because we need to have cookies enabled for sessions to work. We do this by adding two more options.
1
2
3
4
5
6
7
8
9
10
<?php
curl_setopt_array($ch, array(
    CURLOPT_URL => 'http://example.com/wp-login.php',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $postData,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_COOKIESESSION => true,
    CUROPT_COOKIEJAR => 'cookie.txt'
));
The new options are:
·         CURLOPT_COOKIESESSION – if set to true, cURL will start a new cookie session and ignore any previous cookies
·         CURLOPT_COOKIEJAR – this is the name of the file where cURL should save cookie information. Make sure you have the correct permissions to write to the file!
Now that we’re logged in, we only need to reference the cookie file for subsequent requests.
Working with FTP
Using cURL to download and upload files via FTP is easy as well. Let’s look at downloading a file:
1
2
3
4
5
6
7
8
9
<?php
curl_setopt_array($ch, array(
    CURLOPT_URL => 'ftp://ftp.example.com/test.txt',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERPWD => 'username:password'
));

$output = curl_exec($ch);
echo $output;
Note that there aren’t many public FTP servers that allow anonymous uploads and downloads for security reasons, so the URL and credentials above are just place-holders.
This is almost the same as sending an HTTP request, but only a couple minor differences:
·         CURLOPT_URL – the URL of the file, note the use of “ftp://” instead of “http://”
·         CURLOT_USERPWD – the login credentials for the FTP server
Uploading a file via FTP is slightly more complex, but still managable. It looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
$fp = fopen('test.txt', 'r');
curl_setopt_array($ch, array(
    CURLOPT_URL => 'ftp://ftp.example.com/test.txt',
    CURLOPT_USERPWD => 'username:password'
    CURLOPT_UPLOAD => true,
    CURLOPT_INFILE => $fp,
    CURLOPT_INFILESIZE => filesize('test.txt')
));
curl_exec($ch);

fclose($fp);
curl_close($ch);
The important options here are:
·         CURLOPT_UPLOAD – obvious boolean
·         CURLOPT_INFILE – a readable stream for the file we want to upload
·         CURLOPT_INFILESIZE – the size of the file we want to upload in bytes
Sending Multiple Requests
Imagine we have to perform five requests to retrieve all of the necessary data. Keep in mind that some things will be beyond our control, such as network latency and the response speed of the target servers. It should be obvious then that any delays when issuing five consecutive calls can really add up! One way to mitigate this problem is to issue the requests asynchronously.
Asynchronous techniques are more common in the JavaScript and Node.js communities, but briefly instead of waiting for a time-consuming task to complete, we assign the task to a different thread or process and continue to do other things in the meantime. When the task is complete we come back for its result. The important thing is that we haven’t wasted time waiting for a result; we spent it executing other code independently.
The approach for performing multiple asynchronous cURL requests is a bit different from before. We start out the same – we initiate each channel and then set the options – but then we initiate a multihandler using curl_multi_init() and add our channels to it with curl_multi_add_handle(). We execute the handlers by looping through them and checking their status. In the end we get a response’s content withcurl_multi_getcontent().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
// URLs we want to retrieve
$urls = array(
    'http://www.bing.com',
);

// initialize the multihandler
$mh = curl_multi_init();

$channels = array();
foreach ($urls as $key => $url) {
    // initiate individual channel
    $channels[$key] = curl_init();
    curl_setopt_array($channels[$key], array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true
    ));

    // add channel to multihandler
    curl_multi_add_handle($mh, $channels[$key]);
}

// execute - if there is an active connection then keep looping
$active = null;
do {
    $status = curl_multi_exec($mh, $active);
}
while ($active && $status == CURLM_OK);

// echo the content, remove the handlers, then close them
foreach ($channels as $chan) {
    echo curl_multi_getcontent($chan);
    curl_multi_remove_handle($mh, $chan);
    curl_close($chan);
}

// close the multihandler
curl_multi_close($mh);
The above code took around 1,100 ms to execute on my laptop. Performing the requests sequentially without the multi interface it took around 2,000 ms. Imagine what your gain will be if you are sending hundreds of requests!
Multiple projects exist that abstract and wrap the multi interface. Discussing them is beyond the scope of the article, but if you’re planning to issue multiple requests asynchronously then I recommend you take a look at them:
Troubleshooting
If you’re using cURL then you are probably performing your requests to third-party servers. You can’t control them and much can go wrong: servers can go offline, directory structures can change, etc. We need an efficient way to find out what’s wrong when something doesn’t work, and luckily cURL offers two functions for this:curl_getinfo() and curl_error().
curl_getinfo() returns an array with all of the information regarding the channel, so if you want to check if everything is all right you can use:
1
2
<?php
var_dump(curl_getinfo($ch));
If an error pops up, you can check it out with curl_error():
1
2
3
4
5
6
7
8
<?php
if (!curl_exec($ch)) {
    // if curl_exec() returned false and thus failed
    echo 'An error has occurred: ' . curl_error($ch);
}
else {
    echo 'everything was successful';
}
Conclusion
cURL offers a powerful and efficient way to make remote calls, so if you’re ever in need of a crawler or something to access an external API, cURL is a great tool for the job. It provides us an nice interface and a relatively easy way to execute requests. 

How to change the PHP version for subfolders or subdomains

  How to change the PHP version for subfolders or subdomains Setting a specific PHP version for a specific websites, subfolders or subdomain...