Posts about "PHP"

Property hooks are coming in PHP 8.4

— Accessing or setting the value of a class property is comman task in object oriented programming. There are a few ways to do this in PHP. Let’s discuss them first.

Using Google's Gemini AI in PHP

— Generative AI is all the rage these days. Many big players (OpenAI, Meta, Microsoft) have already launched their own AI models that can generate images, text, and even code. So, it’s only natural that Google has also joined the bandwagon and launched its own AI model called Gemini recently.

Convert HTML to PDF using Headless Chrome in PHP

— There are times when you want to convert HTML to PDF. For instance, if you’re building a web application that allows users to generate PDFs of their invoices, you might want to convert the HTML of the invoice to PDF. Or if you’re building a blog, you might want to convert your blog posts to PDFs.

Checking the type of a string in PHP

— If you’re working with PHP, you might have come across a situation where you need to check the type of the string. For instance, you might want to check if the string is a number, alphabetic, alphanumeric, or a binary string.

Managing Git Hooks using Whisky in PHP

— Git hooks are scripts that run automatically every time a particular event occurs in a Git repository. They let you customize Git’s internal behavior and trigger customizable actions at key points in the development life cycle.

Two ways to merge arrays in PHP

— If you’re a seasoned PHP developer, you must have come across the need to merge two or more arrays in PHP. And the bona fide way to do this is by using the array_merge() function.

PHP type declarations — A guide for beginners

— PHP 7 introduced a lot of new features to the language. One of them is the ability to declare the type of a function argument and the type of value that a function returns. This is called type declaration.

The true type in PHP 8.2

— The latest and greatest version of PHP, PHP 8.2 is going to be released soon and it’s going to bring a lot of new features and improvements. In this post, I’ll talk about one of the new features in PHP 8.2 which is the true type.

Converting PNG images to WebP using PHP

— Converting images from one format to another programmatically is sort of a common task. For example, you may want to convert all your PNG images to WebP format to save bandwidth and improve the performance of your application.

Human readable number formatting in PHP

— Numbers are tricky. Numbers are tricky because they have been used as a metric for a lot of things. Currency, scale, weather, science to name a few. And since numbers are associated with several different things, it’s important to represent them in a way humans can understand.

Readonly properties are coming in PHP 8.1

— PHP, as a language, is ever-changing and ever-evolving. It’s not a language it was 10 years ago. This is all because the PHP’s core team which has been constantly improving minor things that might not look significant at first glance but when fixed/implemented, can dramatically improve the overall developer experience.

Native enumerations (enums) are coming in PHP 8.1

— Enums or enumerations or enumerator types are those little data structures that can be used to define a set of named values. More like constants. For instance, a contract status which can be “permanent”, “temp”, or “apprentice”. Or a order status that can be “ordered”, “dispatched”, “shipped” etc.

Array unpacking with string keys coming in PHP 8.1

— The spread operator in PHP is getting more awesome in PHP 8.1! So, to give you a primer, with the release of PHP 7.4, it got possible to merge multiple arrays by unpacking arrays into another array using the spread operator.

Using throw as an expression in PHP 8

— Up until now, when you want to throw exceptions from your code, you would use the throw keyword to throw the exception which can be caught by the catch block like so.

The get_class() alternative in PHP 8

— If you’re working with PHP for a while, there might be a good chance that you’d be in need to fetch the class of an object. This could be mostly for debugging purposes.

Exciting new features and improvements in PHP 8

— As the official release date (26th November 2020) of PHP’s latest and greatest version PHP 8 is approaching, let’s take a look at every new feature and improvement that the PHP team has managed to fit in this version.

Proposed named arguments in PHP 8

Update: Named parameters have been accepted to be included in PHP 8. A 2/3 majority in voting from members was required and it got the required votes! Here’s the RFC that got accepted.

The mixed type of PHP 8

— Up until now, or precisely before PHP 8, whenever you were unsure about which type to use for the propperty or return type, you’d leave it without assigning any type. And if you’re using an IDE such as PhpStorm, the docBlock would mark those properties as mixed type like so.

These new string functions are coming in PHP 8

— Who would’ve thought that PHP would have to wait till its version 8 or rather 25 years after its inception, to get a truly native and understandable function to check if a string is contained in another string?!

Constructor Property Promotion in PHP 8

— Wouldn’t it be nice if you don’t have to declare the class property over and over again just to use it across the class? Currently, you’d do it by first declaring it…

This nullsafe operator could come in PHP 8

— Have you ever wanted a feature where you would only want to call a method or fetch a property on the result of an expression if it is not null? So, for instance, check the following code.

Strict typing vs. Weak typing in PHP

— With PHP 5, the core team had introduced type declarations (also known as type-hinting) that allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.

Immediately Invoked Function Expression in PHP

— Sometimes all you need is to define and call function at the same time and only once throughout the scope. Such functions are called as Immediately Invoke Function Expression (IIFE) also known as Self-Executing Anonymous Function.

Benefits of using custom exceptions in PHP

— Exceptions are really useful when you want to handle some situations which can not be handled gracefully otherwise. So, using exceptions, you can handle certain sceanrios by showing a nice error message. Take the following example for instance.

Using arrow functions in PHP 7.4

— When PHP 7.4 released, it came with a whole lot of features/improvements that makes the language more interesting to work with. The one such feature that I want to talk about is arrow functions. For a primer, arrow functions are not new. In fact, If you’ve been working with the latest JavaScript (EcmaScript 6), you might’ve worked with arrow functions already.

Constructor property promotion could be coming to PHP

— Have you ever felt the class properties that you’re using in the constructor are essentially repeated multiple times? i.e At the declaration, in the constructor parameters and while doing assignment in the constructor. For instance, take the following example.

Computed properties and methods in PHP

— Sometimes, it’s handy if we have an ability to create property and method names from another properties just like what we have in JavaScript. In another words, a property or method name which can be set and used dynamically. For instance, a normal property can be set with a statement in PHP like so.

Multiple constructors in PHP

— Constructors are a really important part of the class-based object oriented programming. Through constuctors, a newly created objects initialize properties automatically before it is usable. In PHP, a constructor is a method named __construct(), which the keyword new automatically calls after creating the object. Constructors can also accept arguments, in which case, when the new statement is written, you also need to send the constructor arguments for the parameters.

Remembering what spaceship operator do on comparison in PHP

— PHP has introduced an operator called “spaceship opearator” (<=>) with the release of PHP7. What this spaceship operator do is compare two expressions i.e. its two operands, let’s say $a and $b, and returns -1, 0 or 1 when $a is respectively less than, equal to, or greater than $b.

Using register_shutdown_function() instead of desctructor in PHP

— The usual and might be the most used way of cleaning the object is to use the good old __destruct() magic method in PHP. The magic method proves to be good in most of the cases. But there might be some scenario where even the __destruct() method will fail. For instance, a scenario where your PHP script exceeds the maximum execution time, and terminates thusly. And a fatal error would occur called Maximum execution time of 20 seconds exceeded in - on line XX.

Some lesser known facts of Traits in PHP

— Traits in PHP is a way of re-using the code. Basically, Traits are assistive copy-paste mechanism provided by the language itself. Using Traits, developers can reduce the limitations of single inheritence based languages such as PHP. I have written a dedicated article about it if you want to check it out.

Little trick to loop through class properties in PHP

— There’s this little trick in PHP that I got to know about today. The trick basically is, you can loop through all the class properties having the “public” visibility just by iterating over the class object using loop construct such as foreach.

Verify if email is from a valid domain in PHP

— Working on an application which received user signups and let’s suppose it’s built on top of PHP, you want to validate that the email the user enters is valid. Sure, you’ll check that the email entered is a “syntactically” valid one by using one of these methods.

Using objects as arrays (with a real world example) in PHP

— Sometimes, it’s convenient when you could get to access class objects as arrays. For instance, the time when one of the class properties is of type array and you want to manipulate it just like you’d do with an array without exposing it during object creation. I’ve included a real world example of where this could be useful, at the end of the article. So, read on!

Premature optimization is dangerous

— Working with PHP, it would be pretty obvious you’d be worried about the performance of your application. And because of this anxiety, you start to optimize trivial things such as replacing double quotes(“) to single quotes(‘), use echo instead of print_r, or using static methods in order to gain those little performance gains during the initial few days of your application development itself. Optimizing these thigs is good and all.

Top features of PHP 7.4 Explained!

— PHP 7.4 is finally released a few days ago. It’s a fourth feature update to the PHP 7 series and it comes with a very interesting set of features which I’m going to talk about in this article. Some of are very long overdue such as unpacking arrays, typed properties and so forth. However, these all comes with some sort of caveats. Let’s talk about all of the new features in details.

Union types are coming in PHP 8

— In this article, I’m going to discuss about the union types which are going to come in future versions of PHP through this RFC. To understand why and how are union types important in PHP, let’s first understand what are union types.

Built-in password hashing and verification in PHP

— Passwords are an integral part of today’s authentication based web applications. In fact, Passwords have been used since ancient times. Sentries would challenge those wishing to enter an area to supply a password or watchword, and would only allow a person or group to pass if they knew the password. In modern web application passwords are used in combination with usernames to authenticate users. So, basically, we’d need to fields in order to store username and password for each user both of which are supplied by user at the time of signing up to the web application.

Better error handling in core PHP functions using Safe PHP

— Some of the PHP’s core functions are designed in such a way that they do not handle exceptions in a better way. Instead, they just return false if there’s any error. This makes developers to handle those error themselves. Take the example below.

A deep dive into Generators in PHP

— Have you ever stuck in a situation where the code that you’ve wrote uses foreach to iterate over a set of data into an array and which ultimately caused you to exceed a memory? Well, I’ve been to. Many times.

Get grandparent instance of certain class in PHP

— Recently, I stumbled upon a scenario where I had to extend a class. I'm going to explain what issue I had faced and what's the role of using the grandparent instance of the class to overcome that issue in this article.

A closer look at Invokable classes in PHP

— In PHP, Invokables refer to any class that may be instantiated without any constructor arguments. In other words, one should be able to create an instance solely be calling new $className(). To implement an invokable class, one needs to use __invoke() magic method of PHP. Before we understand how invokable exactly works, let’s take a look why invokable classes even exists in PHP.

PHP 7.4 will support first-class property type declarations

— With the introduction of scalar type declaration and return type declaration in PHP 7.0, the language’s type system got improved at some extent. Although it’s great to have some layer of strictness, it’s still missing the support to declare typed properties. But from PHP 7.4, it seems, it’s going to change because according to this accepted RFC, PHP 7.4 will be getting support for first-class property type declarations.

Packages to make your Laravel development experience awesome.

— While developing applications(not necessarily with Laravel), you come across the situation where you need to implement certain functionality. In such cases you shouldn’t want to reinvent the wheel if the functionality is been implemented by someone as a package, accepted well by the community and is ready to be consumed. It’s a no-brainer. I use to follow the same approach and today in this article, I’m going to list out some of my favorite Laravel packages which have made my experience with development in Laravel delicious.

Why you should use Laravel Queues

— There comes times when you wouldn’t want your end users staring at white screens or that intimidating loaders for a long time. For instance when user registers to your site, you must have configured your website to send a welcome email or a confirmation email upon registering. So, that operation should be snappy and for that purpose you’d actually want to reduce the amount of time your app takes while sending the email to the user. Laravel Queues comes to the recue for achieving such kind of time consuming tasks.

Top fetaures of PHP 7.3

— PHP development team has just released PHP 7.3 with general availability. This release brings general improvements along with some new features. Even though this is a stable release, the team hasn’t provided concrete migration guide if you want to migrate from the older PHP versions. Maybe they will release those on a later date.

Array destructuring in PHP

— Folks who are familiar with the JavaScript’s ES6 may very well aware of the destructuring feature which allows us to extract data from arrays, objects, maps and sets. For instance, Using ES6 way, we can assign the top level variables of the objects to local variables using destructuring like below:

Using private repositories as a composer package in PHP

Composer is the goto method of adding dependencies in modern PHP application. You search for a library for a concerned functionality and you’ll probably find the one in the large database of the Pacakgist. But there comes a time where you’d want to use a library which is private and should be only available to you. Well, the good news is, you can achieve this using this trick.

Laravel - Accessors & Mutators

— Accessors and mutators allow you to format Eloquent attribute values when you retrieve or set them on model instances. I’ll explain how you can you use them into your app.

Laravel Eager Loading - load() Vs. with()

— Today, while working with one of my projects(which is built on top Laravel) I bumped into the situation where I needed to get associated model’s data for one of the models. So here, I had two approaches in Laravel to accomplish this which are basically called Eager Loading: