PHP : object oriented concepts : Glimpse : Part 3 - Advance Concepts
Pankaj Raundal
Technical Lead at Lionbridge | AWS | Azure | Python | Drupal developer
In this third and last part of oop concepts series we are continue to see some more advance concepts like Static Methods, Class constants, Namespaces, Autoloading, catching exceptions etc....
Class Constants:
In any point of time if you have a important string or any values which is not going to change, instead of using these directly in your class, add those as constant with proper documentation.
Following is the syntax to define constant in your class
// Add some documentation over here so other developers can understand why this constant has been define and used.const VALUE_THAT_NOT_GONA_CHANGE = “this will not gone changes”;
To use these constants in your class or outside of class following will be the syntax,
YourClassName::VALUE_THAT_NOT_GONA_CHANGE
OR
Another way to access constant in same class
Self:: VALUE_THAT_NOT_GONA_CHANGE
Here for constants, we are not referring these properties using object, which we normally do, rather we are directly referencing it using the class name.
So here we can say that Constants are Static. i.e., they are global to the all objects of a class and can be refer by anywhere.
Static Properties:
Considers a case for our classes Product if we have some property and we want it to be globally available for all objects of Product, then we need to make that property Static.?for E.g.
private static $name;?
Now this $name property will be share all objects of Product and has same value.
Here understand that classes are blueprint for the products and objects are actual physical products, each product has a different name, so it makes sense not to make $name as static property instead keep it non-static.
Let’s understand which property we can make static,?
consider we have another property “minimumOrderQuantity”, this property tells what will be the minimum order quantity for each of product. We can set It to “1” so all objects have this common property, we are assuming it's not going to change.?This is the perfect candidate for the static property.
Static Methods:
Above description give us some clarity what is static and when to use it, now lets understand when to make method static, for this you need to find answers for below questions
1)??Is it fine if my method directly attached to class instead of an object?
2)??Does my method needs “$this” variable, does it going to access any non-static property or method at any point of time?
If answers for Q.1 is Yes and answer for Q.2 is No then you can make your method static,?
Functionality inside the static method should be global for all objects and it does not have access to any non-static property. Syntax for static method is as follows
public static yourStaticMethod();
To call static method
YourClassName::yourStaticMethod()
It's totally up to us what approach we want to follow, but the best one is to keep all property non-static first and then decide if it should be static or not on the basis of its usage and functionality it contains.
Namespace and Use statement:
This is very simple concepts and it help to organize your classes in more sophisticated way, Consider a scenario where you have two classes with same name and you want to refer one of them? How?
This case will not arise if you are controller of your code, but what if you are using some third-party library, now you don’t have control over it,
So here namespace comes to rescue, you need to add namespace for each of your class,?Syntax is as follows
namespace ProductManager;
Under this namespace we can add both our Product and GroceryProduct Classes.
We refer at the time of creating object and accessing static properties of class.
With namespace there are two way we can refer these classes on another page,
领英推荐
AutoLoading :
If in past you worked on PHP, we always have bootstrap file which contains require statements for each of the class and we refer this on every other pages where we need to use those classes.
In modern PHP require statements are no more in use, where they gone? are those no more valid? No these are still valid, but approach has been changed to refer these classes. It is called Autoloading.
With the help of use statements, we can utilize Autoloading very efficiently.
As we saw our classes are either model and service and they are reside in different folders as per the type, so we can us folder name as namespace for those classes.
For autoloading we can use following special function,
Spl_autoload_register(function($className) {
?$path = DIR_.’/<yourClassesFolderPath>/’.str_replace(‘\\’,’/’,$className).’php’;
If(file_exist($path)) {
Require $path;
}
});
That’s it, this way you don’t need require statement anymore, PHP will check for above function before throwing class not found error. And if class file exist on correct path it will include the class file and execute the script.
While using autoload we need to follow below points,
Composer Autoloading:
There are PSR standards, some of them are
Composer are generally used to manage dependencies,
You can download composer from https://getcomposer.org/ and install on your system as per your OS.
autoloading can be manage through composer, and we don’t need to write the autoload function which we have saw earlier. We need to create composer.json file and then add following lines to it,
{
? “autoload”: {
? ? “psr-4”: {
? ? “”: “<youFolderNameWhichContainsAllYourClasses”
? ? }
? }
}
After that run “composer install” command, it will create a “vendor” directory on your root with autoload.php file.
This autoload.php file needs to include in your common bootstrap.php file.
That’s it, now you can add as many classes as you want without worrying about require statements.
Exceptions:?
As we saw earlier, we have minimumOrderQuantity property, assume some one try to pass nonnumeric value to it what will happen? Our logic bases on numeric value will not work, and we may face issues due to this, here we can use PHP core Exceptions.
PHP has core class name 'Exception'. This help us to handle such situation efficiently. We can add a exception and check if correct value has been passed or not, either we can stop execution by adding die statement or we can catch?the exception and add proper logic for the same i.e recover from the exception and continue our other code execution.
This gives us more control and allow us to efficiently manage our code logic.
Let’s take another scenario, where we are creating object from the DB table “Product” and return those list of objects as array to display on view page. Here if someone passed incorrect Table name to the method which does above task for us then This will be serious problem for us and we will get fatal error and PHP will halt the execution.
What if we identify such scenarios in first place and handle those. We can do the same by using try-catch block. Something like below,
Try {
? ? // Code which utilise ‘product’ DB table to create object
? ? // Those lists of products will get displayed on page
? ? Return $products
} Catch (\Exception $e) {
? ? $products = [];
}
Here try block will execute normal code and try to create a object from product. If we get any error here it will throw an exception which will get caught in catch block. In the catch block we can pass blank product array, now instead of getting ugly errors user can see the page with blank product listing with some nice message.
Also catch block provide us an opportunity to log error message and that will help us to identify and debug the issue.
You can create your own custom Exception by extending core Exception class.
PHP also provide various classes which are useful to catch the particular type of exception, like PdoException, InvalidArgumentException. etc…These classes are extended from Exception class.
That's it for the oop concepts, this was more theoretical but it help to clarifies the some oop concepts.
In any field where you work, your basic needs to be clear. Then and then you can perform with your full potential. In programing, object oriented concepts are the basics. Any programmer irrespective of any programing language needs to be clear about these concepts.
Its like a Car, once you have all your basic regarding driving and tools are covered, your ride will be smooth and don't face many issue in your journey, but if you are in doubt and not sure about things, then it will be difficult to manage the situation. Same with programming, you should cover all your basics.
If you come to this part of article then please share your thoughts. Any suggestions are always welcome.