Thursday 6 December 2012

Understanding Abstract Classes in PHP

Abstract classes are an often misunderstood feature of PHP object-oriented programming (OOP) and the source of confusion when considered versus an Interface. The obvious reason for using an Interface is that a child class can implement multiple interfaces but extend only a single abstract class. However, if multiple inheritance is not required then people often go with abstract classes just because they provide the option of later adding base functionality within the abstract class. This is not entirely unreasonable but the reasons for creating abstract classes should be more than that.
Why Use Abstract Classes?

An Abstract class provides concrete base functions as well as abstract functions that must be implemented by concrete child classes—binding them into a contract so to speak, if they wish to make use of the base functionality.

This is a subtle but important point and this is where abstract classes really shine. They can call abstract functions from within base concrete functions. Jumping straight to an example is the clearest way to explain this.

[sourcecode language="php"]
abstract class Animal {
function greeting() {
$sound = $this->sound(); // exists in child class by contract
return strtoupper($sound);
}
abstract function sound(); // this is the contract
}

class Dog extends Animal {
function sound() { // concrete implementation is mandatory
return "Woof!";
}
}

$dog = new Dog();
echo $dog->greeting(); // WOOF!
[/sourcecode]

This opens up a whole lot of interesting possibilities. For example, you can write a drive() function that calls $this->start(); $this->accelerate(); in an abstract class. Then create a motorcycle class that defines its own start() and accelerate() functions that may be different from those in the car class. In turn, the motorcycle and car can both be driven by just calling drive() without having to implement it locally.
Characteristics of Abstract Classes

Make a note of these characteristics to lock down your understanding of abstract classes:

  • Single inheritance. Child classes can extend only one class at a time.

  • Abstract classes cannot be instantiated — no new Animal();

  • Abstract classes can define class variables of type const only.

  • Abstract class A can be extended by another abstract class B. Abstract class B can implement none or any of the abstract functions in A.

  • In the previous case, a child class C which extends abstract class B must implement all abstract functions in B as well as the abstract functions in A which have not already been implemented in B.

  • The signature of the concrete functions and abstract functions must be the same. However, if an abstract function is defined as abstract function speak($greeting); then it is okay to implement it as function speak($greeting, $shout = FALSE) but not function speak($greeting, $shout).

  • The visibility of functions in the child classes must be the same or less restrictive than the parent class. Thus, a protected abstract function can be implemented as either protected or public but not private.

  • Declaring functions as static abstract throws a strict warning in PHP 5.2 or earlier, however, as of PHP 5.3 this is allowed.

Friday 25 May 2012

Writing Your First Twitter Application with oAuth

Hello Friends

In My current application There is requirement to fetch twitter timeline for the particular user. So I’ve fetched it with the help of Rest API of twitter an oAuth.

OAuth is an open protocol to allow secure API authorization in a simple and standard method from desktop and web applications. In layman’s terms, it is a system by which you can allow a user to authenticate with an OAuth-enabled service without providing you with their credentials to that service.

Why OAuth?


Using OAuth allows you to write applications that access the Twitter API but do not require your users to give you their Twitter username and password. This is important for a variety of reasons:

  • If the user changes their Twitter login, they do not have to update that information with you for your application to continue working for them

  • Using OAuth puts the user in control – if they ever wish to stop using your application, they can disable it through Twitter instead of trusting your application to stop using their login information. Once they disable it through Twitter, any requests by your application will require them to manually approve the connection again.

  • Increased sense of trust, since the user doesn’t have to worry about your application stealing their Twitter credentials and using it for nefarious purposes. I personally wouldn’t trust any web-based application that asks for my Twitter username and password, and given Twitter’s recent history of bad press regarding their security, more and more users are following that lead.


Getting Started – Registering Your Application with Twitter


First of all , you have to register your new application with Twitter. You’ll need a name and url for your application in order to register it, and you’ll need to define a callback url. The callback url is the full url of the page Twitter should send the user to after it’s done authenticating. This file can be named anything you want, but make sure the one you create on your server matches the one you register with Twitter. All of these details can be changed later if you change your mind or need to update something.

Once you’ve registered your application, Twitter will issue you a Consumer Key and a Consumer Secret for your new app. You’ll need these to get your sample code from the Twitter OAuth library working. As you can probably tell by the name, your Consumer Secret should remain private and you should never give it out to anyone. It’s used in your code so that Twitter can identify your application when you’re making API calls.

By forcing you to send your consumer key and secret with your API calls, Twitter is able to determine which application is sending the API calls, and can verify that the Twitter user you are attempting to send API requests on behalf of has actually authorized your application to access their account. If the user decides they no longer want to allow your application, they can edit their allowed application preferences and your application will no longer be able to make API calls on their behalf.

You can access a list of all of the applications you have registered with Twitter – and links to edit their details or view the consumer key and consumer secret – by going to your oauth clients page on Twitter.

The Twitter OAuth PHP Library Code


There are several oAuth Twitter -libraries for PHP. But I Recommend Abraham’s Twitter OAuth library . You can pull the code from http://github.com/abraham/twitteroauth.

This library does provide an example script. You need to replace your Consumer Key and a Consumer Secret in confing.php. Please check that callback.php file should be one that we’ve registered with Twitter as being our callback url. We can keep common configuration options such as the consumer key and consumer secret, and database credentials in a config.php file. Now you can run index.php.

Now in your callback.php you can save access_token in database for future request. You can use that access token to call the APIs and you don’t need to enter Twitter user name and password.

[sourcecode language="php"]
/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
/* Request access tokens from twitter */
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
[/sourcecode]

Here you can dowanload the whole code from git hub. you just need to put your Consumer Key and a Consumer Secret in config.php and need to check callback url settings it should be demo's callback.php and than you can run index.php you will get the result.

https://github.com/viralsolani/twitter-oAuth-example

Important Links

Hope it helps

 

Thursday 24 May 2012

PHP SDK & Graph API base Facebook Connect Tutorial

Hello Friends

In My current application I've used facebook Graph API to fetched data from facebook with the help of  PHP SDK. I've explored so many tutorials on web but I found some links are very helpful and easy to understand Here I'm sharing those links. By surfing through these links you can get to know these below things

1 . How you can create your application in Facebook and How you can use APP ID and APP Secret? 

2. How you can connect to Facebook from your Application?

3. How you can fetch data with the help of Facebook Graph API and PHP-SDK?

4. How you can Design your Facebook Application?

So here are some useful links.

  1. http://www.londatiga.net/it/how-to-create-facebook-application-with-php-for-beginner/

  2. http://thinkdiff.net/facebook/php-sdk-3-0-graph-api-base-facebook-connect-tutorial/

  3. http://net.tutsplus.com/tutorials/php/wrangling-with-the-facebook-graph-api/

  4. http://www.joeyrivera.com/2010/facebook-graph-api-app-easy-w-php-sdk/

  5. http://net.tutsplus.com/tutorials/javascript-ajax/design-and-code-an-integrated-facebook-app/


To Create a New Application in Facebook.

https://developers.facebook.com/apps
Graph API

https://developers.facebook.com/docs/reference/api/
PHP SDK refrence

https://developers.facebook.com/docs/reference/php/
FB Tool for Graph API Explorer

http://developers.facebook.com/tools/explorer

Hope it helps.


profile for Viral Solani at Stack Overflow, Q&A for professional and enthusiast programmers

Tuesday 24 April 2012

Autoload your classes in PHP

Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn’t been defined yet.

This is how it works in action. We will create two classes. So create Image.php file and paste this in:

[sourcecode language="php"]
<?php
class Image {
function __construct() {
echo 'Class Image loaded successfully <br />';
}
}
?>
[/sourcecode]

Now create Test.php file and paste this in:

[sourcecode language="php"]
<?php
class Test {

function __construct() {
echo 'Class Test working <br />';
}
}
?>
[/sourcecode]




Basically, we created 2 simple classes with constructors which echo some text out. Now, create a file index.php and paste this in:


[sourcecode language="php"]
<?php
function __autoload($class_name) {
require_once $class_name . '.php';
}

$a = new Test();
$b = new Image();
?>
[/sourcecode]





When you run index.php in browser, everything is working fine (assuming all 3 files are in the same folder). Maybe you don’t see a point, but imagine that you have 10 or more classes and have to write require_once as many times.

I will show you how to properly throw exception if you are using PHP 5.3 and above. Chane your index.php to look like this:
[sourcecode language="php"]
<?php
function __autoload($class_name) {
if(file_exists($class_name . '.php')) {
require_once($class_name . '.php');
} else {
throw new Exception("Unable to load $class_name.");
}
}

try {
$a = new Test();
$b = new Image();
} catch (Exception $e) {
echo $e->getMessage(), "\n";
}
?>
[/sourcecode]





Now, it checks if file exists and throws a proper Exception if it doesn’t.

That’s it. A handy functionality to spare some typing.

Sunday 18 March 2012

PHP 5.4 is Released — What’s New?

It’s difficult to believe almost three years have elapsed since PHP 5.3.0. The next version should have been PHP 6.0 but unicode problems have delayed development. This latest version provides many of the features planned for version 6.0.

PHP 5.4 is available to download from the php.net website. There’s a PHP 5.3 migration guide if you want to keep your old settings. While it’s stable, you’d be advised to test your sites and applications before installing it on live servers. The PHP team often release a bug-fix version a few weeks after the initial release.

So let’s look at the best new features and improvements…

Short Array Syntax


It’s now possible to use finger-saving JavaScript-like square brackets rather than using the old array(…) construct, e.g.


  1. $array1 = [1, 2, 3];

  2. $array2 = [

  3. "one" => "first",

  4. "two" => "second",

  5. "three" => "third"

  6. ];



Traits


Traits reduce some limitations of single inheritance. In essence, traits are similar to abstract classes and can contain any number of properties and methods. A class can then use any number of traits, e.g.



  1. trait Hello

  2. {

  3. function sayHello() {

  4. return "Hello";

  5. }

  6. }

  7. trait World

  8. {

  9. function sayWorld() {

  10. return "World";

  11. }

  12. }

  13. class MyWorld

  14. {

  15. use Hello, World;

  16. }

  17. $world = new MyWorld();

  18. echo $world->sayHello() . ' ' . $world->sayWorld();



For more information, refer to Using Traits in PHP 5.4 on PHPmaster.com.

Built-in Web Server


PHP 5.4 offers a built-in web server which runs from the Windows, Mac or Linux command line. While it’s not Apache or IIS, it’s fine for simple testing. I suspect many of the better PHP IDEs will implement support shortly.

For more information, refer to PHP 5.4′s New Built-in Web Server.

New Commands


A number of useful commands have been implemented:

  1. hextobin(string $hex): coverts a hex representation of data to binary.

  2. http_response_code(int $code): allows you to set or get the HTTP response code, e.g. http_response_code(404);

  3. header_register_callback(string $function): allows you to register a function which is called when PHP starts sending output.

  4. trait_exists(string $name [,bool $autoload]): determines whether a trait exists and, optionally, whether it should be autoloaded.


Miscellaneous Updates


If that’s not enough…

  • Class members can be accessed on instantiation, e.g. (new MyClass)->MyMethod()

  • <?=$variable?> is always available regardless of how your short_open_tag ini option is set.

  • Binary numbers can be declared, e.g. 0b11110000

  • Session upload progress has been implemented so PHP can track the state of file uploads.

  • Some users are reporting speed increases of up to 25% with a memory reduction of 35%.


Compatibility Issues


Most older PHP code should run without modification but there are a few gotchas to look out for:

You should also note that PHP 5.4.x will be the last edition to support Windows XP and Windows 2003.

PHP 5.4 isn’t quite as radical has 5.3, but there are enough new features to keep developers happy for a while. Let us know if you have any positive or negative experiences with the latest version.

Tuesday 17 January 2012

Regular Expressions Cheat Sheet

The Regular Expressions cheat sheet is a one-page reference sheet. It is a guide to patterns in regular expressions, and is not specific to any single language.

regular-expressions-cheat-sheet