To return an image as a request response by PHP you fpassthru function of PHP. I have included a sample code snippet, which will help you to understand how to do this.
From the above code snippet, you can see I have opened an image with binary mode by fopen($image, ‘rb‘). And then send that with appropriate headers by header(“Content-Type: image/png”). After that dumping that image by using fpassthru, and finally stop the execution of PHP. It’s really easy to return image as response by PHP
What’s up, guys! Hers I am going to describe you the dependency Injection in PHP.
Dependency Injection in PHP:
Do you actually know what does it mean? Normally dependency injection means to inject something to another stuff. In programming concept, it means to inject an object to another class to perform an operation. In Software engineering dependency injection is really useful and handy design pattern. Programmers are widely using this design pattern to make their code more usable, testable and highly maintainable.
Programmers are always thinking how to manage their dependencies. They want to write good application code with avoiding dependencies. Here is the solution comes from design pattern concept to avoid the dependencies problem. I will use some code snippet to make you understand what is dependency Injection, why and how to use it.
Dependency Injection in PHP
Look at this code snippet:
At first glance of this code snippet, you might think there is nothing wrong with this code, For a moment I agree with you. But! if we have closer look on it then you can understand the problems of this code such as.
Here you can see the __construct of student class are creating an instance/object of course class. Which means we already written a hard-coded dependency for the student class. So the student and the course class are tightly coupled together. If we want to create instance/object of student class then we have to pass arguments for course class also. Cause student’s __construct is already creating instance/object of course class.
Now let’s imagine we made a change on course class. Suppose we add a new parameter in __construct method in course class. Then every class we need to change who created instance/object of course and they need to pass an extra parameter into course class.
Identifying The Problems:
Here you can see we added a new parameter into course class called lesson. And created a new class called department. So here student and department both classes needed course class and they are created instance/object for course class.
After adding a new parameter (lesson) in course class then student and department both classes are modified with passing a new parameter (lesson) to course class.
So every time you will need to do the same thing if the same case will happen. So if you have many classes like that, every class need to modify. And it’s a really annoying and error can occur easily. To avoid this types of scenario programmer are using dependency injection.
Solutions
Look at this code snippet, here you can see in student and department both class __construct needed course instance/object as a parameter (2nd parameter). And is assign into ‘$course’ properties.
We created an instance/object of course class, and while we creating instance/object for student and department then using created course instance/object as arguments.
So that way if we made any class in course class, then we don’t need to modify our student and department class. We just need to change in $course = new Course('English', 2, 5);'
(where the object is created).
With this strategy, you can widely inject your dependency to another class. And your code will more testable and maintainable.
Hope this article hely you to understand what is dependency injection in PHP and how to use it.
I believe you already heard about the PSR in PHP language. Today I am trying to help you to understand the what is PSR, how and why should we use it.
PSR in PHP
PSR knock as ‘PHP Standards Recommendation’ which is some recommendations for all PHP programmer when they write their code they should follow some rules and regulation. With following that recommendations anyone can understand other programmers code. It’s working like an eco-system or uniform system where we all following these systems. Basically, there are five PSR: PSR-0, PSR-1, PSR-2, PSR-3, PSR-4. So let’s see about these five.
PSR IN PHP
Before we move forward we should need to know the history of PSR in PHP language. Honestly, there are no uniform coding standards for writing code for PHP programmer. Some programmer has written their code by with their own naming convention and coding style. Someone was following some framework’s conventions such as PEAR or Zend Framework. So there was a huge problem to understand other programmer’s code. Cause they do not follow any uniform rules and regulation.
With that passing time, FIG (Framework Interoperability Group) intends to introduce a cross-section of the PHP ecosystem, not exclusively framework developers. The main focus of FIG create a dialogue between project representatives, and with this concept, they were searching a suitable and useful way to work together and everyone comes under one ecosystem of PHP and they introduce some PHP Standards Recommendations (PSR-0, PSR-1, PSR-2, PSR-3, PSR-4).
PSR-0:
PSR-0 refers to the ‘Autoloader Standard’. it comes with huge advantages to reusable the codes and loading the classes. Before the PSR-0 has come, we were working with PHP 5 magic function _autoload() which is automatically loading the class we required and gives us a flexible way to create the instance that class. But with _autoload() you can able to provide only one autoloader function. Later PHP 5.12 introduced spl_autoload() which provides to register multiple autoloader function. Then PHP introduces the spl_autoload_register() function which gives us permission to create a series of the autoloading function. After PHP 5.3 PHP support true namespace and then the FIG (Framework Interoperability Group) written some guideline for the PSR-0. Below are the requirements for PSR-0 compliance:
A fully-qualified namespace and the classes must have the following conventions <Vendor Name>(<Namespace>)*<ClassName>.
Each and Every namespace must have a top-level namespace (“Vendor Name”).
A namespace can have as many as sub-namespaces according to need.
Namespace separator converted into DIRECTORY_SEPARATOR.
Underscore in the class name converted into DIRECTORY_SEPARATOR.
Vendor names, namespaces, and class names might be of any combination of lowercase and uppercase.
These are some requirements for the PSR-0.
PSR-1:
PSR-1 refers to ‘Basic Coding Standard’ for PHP programmers. Actually, PSR-1 focus on the naming convention, file structure etc. With these rules, the code is understandable to all programmers who follow the PSR-1 Rules. Below are the requirements for PSR-0.
Only allow to write <?php and ?> (<? and <? are not allowed) tags for PHP.
Only allow using UTF-8
Force to use PSR-0
Class name must be in PascalCase/StudlyCaps (that means follow Capitalization Conventions while write class name )
Class constants/global variable must be defined in UPPER_CASE with underscore separators.
Method names must be defined in camelCase.
These are some requirements for the PSR-1.
.PSR-2:
PSR-2 refers to ‘Coding Style Guide’ . Actually PSR-2is the extended and expands of PSR-1’s ‘Basic Coding Standard’. The main goal of the this Standard is moving all PHP programmer to follow a uniform coding guideline
The programmer must follow a coding style guideline (PSR-1).
Code must have 4 space for indenting, tabs are not allowed.
Code should have the length limit (120 characters are known as soft limit and above 120 characters knock as hard limit. The code length limit should be 80 characters or less)
There MUST be one empty line after the namespace declaration, and there MUST be one blank line after the block of use declarations
Opening braces for classes MUST go on the next line, and closing braces MUST go on the next line after the body.
Opening braces for methods MUST go on the next line, and closing braces MUST go on the next line after the body.
Visibility MUST be declared on all properties and methods; abstract and final MUST be declared before the visibility; static MUST be declared after the visibility.
Control structure keywords MUST have one space after them; method and function calls MUST NOT.
Opening braces for control structures MUST go on the same line, and closing braces MUST go on the next line after the body.
Opening parentheses for control structures MUST NOT have space after them, and closing parentheses for control structures MUST NOT have space before.
These are some requirements for the PSR-2.
PSR-3:
PSR-3 refers to ‘Shared Logger Interface’ for PHP programmers. Which is for taking/storing the application/system log reports. When an application is running then sometimes error, notice, alert, can be happened, in this situation we need to track/save these actions, and PSR-3 describe us how should we save these actions.
PSR-3 incorporating with eight Syslog levels of(debug, info, notice, warning, error, critical, alert and emergency), These Syslog levels describe as a function and it’s accept two parameters such as ‘Message’ and ‘Context’. Generally ‘Message’ is a string regarding with logs level and Context is for store additional information.
Recently monolog implemented PSR-3 so you can use monolog for storing your application log.
PSR-4:
PSR-4 is the most recent added by FIG (Framework Interoperability Group). The PSR-4 is working together with PSR-0 where needed. PSR-4 is the replacement of PSR-0. The main goal of PSR-4 is to remove the remnants of PSR-0 and the pre-5.3 days completely and allow for a more concise folder structure. You can see the specifications of PSR-4 from here
Conclusion
The PHP-FIG does a great job of centralizing PHP standards. With this following these standards every PHP programmers will going forward with the same concept. So every PHP programmer should follow these standards, so they can working together.
Factory method design pattern is the most common design pattern in software engineering. It’s deals with creating object of a class without specified the class name. Just simply think there is a factory of creating object of other classes.
For example:
We can see there is two different classes, one is Student and another is StudentFactory. StudentFactory is the factory of creating object of Student class. StudentFactory has a method called create() which used to return the object of Student class. So that we can easily create object of Student class from StudentFactory Class. These are the basic concept of Factory method design pattern in PHP.
Anonymous is a normal PHP function but there is no specified name. Anonymous function seems like a normal/regular PHP function, it’s has a code block and run when it called, return value, it’s takes arguments as well. The major different between regular PHP function and Anonymous function are:
Anonymous function doesn’t need any name to declare the function but regular PHP function must need a name to declare.
Anonymous Function in PHP
From this image, you can see the Anonymous function has no name between function keyword and.
And another major different is Anonymous function has a semicolon (;) after the function definition (see the image above). These are very major different between regular and Anonymous function.
In the a above image’s anonymous function is valid but not callable yet from anywhere. So it isn’t useful, To create a callable anonymous function we need to do a little more. I will show that rest of the article. So don’t worry
The Anonymous function is extremely useful as a value of a callback function. It can be really useful in certain situations as well. I will explain to you how to create an Anonymous function, how to use it and how to use it as a value of callback function.
To create an Anonymous function and access it, you can do a couple of handy things with it. For example,
Create an anonymous function and assign it to a variable, then call that anonymous function by using that assigned variable.
Create an anonymous function and pass it as an argument to another function. (callback function)
Creating Anonymous function and assign into variable:
Create an anonymous function and store that into a variable, Something like that
Here you can see, I have created a function and storing that into $anonymousVariable variable and calling. Now we can call access this anonymous function by using this $anonymousVariable variable. I am calling the anonymous function by this way echo $anonymousVariable('World'); here ‘World’ is the argument of the anonymous function.
From this above code snippet, you will get this output.
PHP Anonymous function
Create Anonymous function and pass it as an argument to another function:
One of the useful use of Anonymous is, build a callback function. A callback is a function (you will create) and passes to another function as an argument. Some PHP built is function allow add custom functions (e.g array_map() ). I will show this example with using array_map() function. See the code snippet below.
From this above code snippet, you will get this output.
So, now you explored about what is Anonymous function and some basic usage of it. Hope this article will help you to understand the about Anonymous function.
One of the huge changes happened in PHP world is the Composer. With the Composer, you can able to use third party libraries in your project. But here I am trying to say that you are using other’s libraries in your project, but why not you also create a library and use that by others as well. This article will cover how to Create Package in PHP, let’s see!
How to Create Package in PHP?
Here I am creating a sample package step by step, so you can see and do it by yourself. First of all, login to your GitHub account and create a new repository called ‘first-php-package‘ .
HOW TO CREATE PACKAGE IN PHP
After creating a repository you will see something like that and now copy that clone URL.
Open your terminal and run this command sudo git clone https://github.com/YOUR_GITHUB_USER_NAME/first-php-package.git. Then open this project with your code editor. And create an src folder, composer.json file in project’s root directory. Open up the composer.json file and paste this code.
Here first-php-package’ is the name of the package, Please don’t change the name cause this must be the same with the GitHub repository name. You can change the other’s metadata as well in the composer.json file. Once you are done with editing the composer.json file then run sudo composer install command.
Go to src folder and create a Hello.php file and paste this code into Hello.php file.
<?php
namespace src;
class Hello {
public function sayHello()
{
return ' This is my first php package';
}
}
Then run sudo composer dump-autoload command. And create a test.php file in your root directory and paste this code.
<?php
require 'vendor/autoload.php';
$helloClass = new srcHello();
echo $helloClass->sayHello();
Finally, commit and push all the code, and browse your project (e.g.http://localhost/first-php-package/test.php)
Now you have the package but you still need to submit that package. Go yo packagist and login by your GitHub account. Then click the ‘Submit Package’ button, after that put your repository URL (in this case repository URL is https://github.com/YOUR_GITHUB_USER_NAME/first-php-package) then check and submit. Now your package is submitted to packagist and anyone can able to use it.
This is really basic way of creating a package and submit into packagist. Hope you can learn from this article how to create and how to submit a package.
Sometimes programmer/developer need to get data between two timestamps from multidimensional array . Here I have written some sort of code for getting data between two timestamps from multidimensional array. I hope that will be helpful for you!
Sometimes we need to sort out multidimensional array by timestamp. Which is really important to programmer/developer how easily they can sort out a multidimensional array by timestamp (Time). I am here to share a script which will be helpful to sort your multidimensional array by timestamp.
Magic method is called some predefined method of PHP which execute some event by the PHP compiler. The method start with the double underscore (__) known as PHP magic method (for example __construct, __destruct, __get, __set, __call etc). This is method is usually use inside any class. PHP has various magic method, I will try to discuss some most common magic method.
__construct:
The __construct method will called when someone create any instance/object of a class. This method usually declared at first of a class, but there is no any strict rules where we need to declare it. We can declare is anywhere in our class. and also we can inherit this method.
__destruct:
The __destruct method is called when object is destroyed, it’s opposite of __construct method. This method usually declared at last of a class, but there is no any strict rules where we need to declare it. We can declare is anywhere in our class.
__get:
The get method is called when anyone want to read/get the value of property or variable.
__set:
The __set method is called when someone want to set value of a property or variable.
__isset:
The __isset method is called when someone applied isset() method anywhere in a class.
__unset:
__the __unset method is called when someone applied unset() method anywhere in a class, which i really opposite of isset method.
__call:
The __call method is called when someone try to call a normal method.
__sleep:
The __sleep method is called when someone trying to serialize his class object.
__wakeup:
The __sleep method is called when someone trying to deserialize his class object.
__toString:
The __toString method is called when someone try to print the object of a class.