Internationalization & Localization Application with CakePHP 3

CakePHP has one of the coolest features to make application Internationalization & Localization. It’s really easy to translate your application or website into multiple languages with CakePHP 3.  Let’s see it.

First of all, create a directory Locale inside PROJECT_ROOT/src

Create a subdirectory of each language (which language you want to translate your application) inside PROJECT_ROOT/src/Locale/. Subdirectory name can be anything (ex. english, french, etc), but prefer ISO code of the language (ex. en_US, fr_FR, bn_BN etc). So follow this tutorial and make your subdirectory name en_USfr_FR, and bn_BN

Create default.po file inside all subdirectories (en_USfr_FR, and bn_BN). And copy the following code in the respective file.

src/Locale/en_US/default.po

msgid "message"
msgstr "Hello World"

 

src/Locale/fr_FR/default.po

msgid "message"
msgstr "Bonjour le monde"

 

src/Locale/bn_BN/default.po

msgid "message"
msgstr "ওহে বিশ্ব"

Here msgid key of which will use inside the template (view files) and msgstr is the values which will gonna translate.

So now you have three different languages (en_USfr_FR, and bn_BN). and one key (message) which can be translated into these three languages.

Now use <?php echo __(‘message’); ?> in your view (any ctp file of your application).

Then open PROJECT_ROOT/config/app.php file and find

 'defaultLocale' => env('APP_DEFAULT_LOCALE', 'fr_FR')

and replace with your language.

But if you want to translate language in runtime then you can use it

use Cake\I18n\I18n;

I18n::locale('fr_FR');

I hope this article will help you to translate your application in multiple language.

CakePHP 3 – DebugKit Toolbar Not Visible

Are you looking for the solution of DebugKit Toolbar not visible in CakePHP 3? These small tips will help you do that. Ensure you have pdo-sqlite installed & enabled on your machine. Cause debugKit by default uses a sqlite db. If not then follow this instruction.

At first install pdo-sqlite in your machine.

sudo apt-get install php7.0-sqlite

Then restart your server (apache server)

sudo service apache2 restart

Now that will help you to visible the DebugKit Toolbar

 

Concurrency Issues With PHP Session

Concurrent connection means how many request sending/calling at the same time. It influences the application performances rapidly. When your application can handle as much as concurrent connections your application will become more stable, high scalable and faster as well. But concurrency might be a problem when you deal with PHP Session. It is the biggest challenges to avoiding concurrency issue in PHP, especially in PHP Session.

Most of the modern web browser sent concurrent connections to a specific domain to between 4 or 6. That means if your application has a lot of static assets (JS, CSS, Images, Fonts, etc), then these will be queued until browser get the response from the server for its first set of a request (4/6 concurrent request).

Concurrency Issues With PHP Session

PROBLEM:

By default, PHP uses files to storing the Session data. PHP either create a new Session or retrieve existing Session on each request when called session_start() function. So in this case, if your user sending multiple concurrent requests to the server which involves with Session data. PHP Session will lock and block your application’s concurrent request for that particular client. And every request will be served as sequentially instead of processing them concurrently.

BEHIND THE SENCE:

For the new user, PHP sent the unique identifier number to users computer and create a new file with the same unique identifier name for handle the session for that particular user. Otherwise, PHP retrieves existing session for that user. See this article to know how does session works.

Now assume, a user sent 6 concurrent requests to server and 4 of them involved with session data. So what happened that case? PHP will take the first request and open the session file and lock it. And other 3 requests will be queued until session file will be released. So that means your application will be blocked. After your first request’s done, it will release the session file and the second request will take it. It’s will happen for rest of the request.

Now think every request taken 400-500 ms to execute, that means your last (4th) request completed after 1600 ms cause it waited 1200 ms to complete first 3 requests. So in this way PHP Session blocked the application.

However, this concurrent issue happened for the same user only. Request from a user cannot block another user’s request.

You will be able to understand how this thing can affect your application performance. To improve application performance every developer needs to avoid this issue.

PSR in PHP

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
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.

 

 

 

 

 

How to Create Custom Filter in Twig

Twig is the Fast, Secure, Flexible, and Powerful template engine of PHP. It has lot’s of great features for develope the front end. It’s has tons of built in filters, but sometimes we need to create our own custom filter and use them into Twig. With this article I am trying to describe you how to create custom filter in Twig.

I am showing an example so you can understand better. Go, where your Twig in loading paste this code.

Here, the custom filter name is ‘convert_object_to_array‘ Which is responsible for convert an object to array. Now you can call that filter in your twig file by {{ objectData | convert_object_to_array }}. Now you can type casting your object into array with this custom filter.

 

 

 

 

What is AngularJS and How to Start

What is AngularJS?

AngularJS is the web application development framework which provides a flexible way to build testable and maintainable front-end applications. Generally, AngularJS javascript MV framework which is developed by google for build dynamic web application. For more details click here.

How to Start?

It’s really easy to start AngularJS. Just need to download AngularJS JavaScript file, and add to your web page with a script tag: You can also add it from remote url (e.g. http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js).  Here is an example code, so you can see how it works.

Explanation of this Code:

Here I will use 3 types of directives of AngularJS  which are:

ng-app:  This directive will define the angular application, That means this ng-app directive is for initializing the Angular into the page.

ng-model: This directive binds/takes the value from HTML controls (input, select, text area) to application data.

ng-bind: This directive  display the application data to the HTML view.

You can see ng-app directive is declared into the body tag that means Angular  is initialized among whole web page.  and the ng-model directive is declared three times called (name, title, and comment) and which was binds by {{name}}, {{title}}, {{comment}}
{{name}} bind for ng-model="name",
{{title}} bind for ng-model="title",
{{comment}} bind for ng-model="comment"

Output

What is AngularJS and How to Start
What is AngularJS and How to Start

Hope you can learn the basic concept of AngularJS from this article. Thanks!!!

How to Create Package in PHP

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
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.

{
    "name": "YOUR_GITHUB_USER_NAME/first-php-package",
    "description": "This is my first PHP package",
    "license": "MIT",
    "authors": [
        {
            "name": "YOUR NAME",
            "email": "YOYUR EMAIL ADDRESS"
        }
    ],
    "require": {
        "php": ">=5.3.0"
 
    },
    "autoload": {
        "psr-0": {
            "src\": ""
        }
    }
}

 

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.

Load jQuery fullcalendar Inside Boostrap Modal

Sometimes we need to load the jQuery fullcalendar inside Bootstrap. But normally fullcalendar is not loading properly inside Bootstrap modal. We need to apply small a tricks to do that. I have written a fiddle for you. To see the demo Click Here (jsFiddle).

Preview:

jquery_full_calendar

Now you are quite able to load your calendar inside your modal.

 

Why Should Use Composer and How to Use It

One of the massive changes happened in PHP world is the Composer. You may be heard about composer but I don’t know either you use it or not. I am here to describe you why should we use composer, how much it is good for you and how to use it. Cheers!

What is Composer?

Composer is dependency management in PHP and it deals with various types of packages or libraries of PHP. Composer allows us to declare/write required PHP libraries/packages  for the project and it will install of those libraries/packages inside your project. And most important it will autoload all the installed  libraries/packages so that you can easily access these libraries/packages classes.

Why Should Use Composer?

We are using 3’rd party libraries/packages in our project. When we need a library then we download that library and store inside somewhere of our project. After that we require/include that library for access it’s classes. And we are doing same thing again and again when we need a another new library. That’s really annoying to a programmer or developer to download and include again and again, isn’t it? OK Composer comes to avoid this problem and provide a flexible way to manage all the packages or libraries inside your project. Together with Composer we have some rules and regulation, creating a PHP project with the same structure, using namespaces, the same code style, etc. For more information visit the composer official website https://getcomposer.org.

How to Use Composer?

Using of composer is really easy. Before you use Composer in your project your need to install Composer in your computer. By the end of this article, you will be able to plug and play with chunks of code in any framework, whether you work with CodeIgniter, FuelPHP, Laravel, Symfony2,Lithium, Yii, Zend… or anything else.

 

Installing Composer:

Installation of composer into you machine is really easy. Here I am showing the installation of composer for Ubuntu (Linux) operating system. If you are using Windows then see here.  Open you terminal and run this commands.

 

$ curl -s https://getcomposer.org/installer | php
$ sudo mv composer.phar /usr/local/bin/composer

 

Setup Project With Composer:

To start using Composer in your project, you need to create composer.json file in your project’s root directory. And write the dependencies of your project (may also contain other metadata as well) in this file. The JSON format is pretty easy to write. It allows you to define nested structures.

With the ‘require’ keyword you can telling Composer which packages you will need to this project. And Composer will download all the packages from Packagist.

{
    "require": {
        "monolog/monolog": "1.0.*"
    }
}

 

Here you can see I have required ‘monolog/monolog’ library with the version ‘1.0’ by using ‘require keyword. Here ‘monolog/monolog’ is the package name and ‘1.0’ is the version of this library.  Go to Packagist and you will get lot’s of php library you wanna need. Packagist is a repository Composer packages. Here you can find packages and lets Composer know where to get the code from.

Now just run ‘Install‘ command to get all the packages in your local project.

 

php composer.phar install

 

After run this command composer will find the ‘monolog/monolog’ library in Packagist and download the latest version in store into ‘vendor’ directory. And you will see a composer.lock file is create in your directory. Now go to created ‘vendor’ directory here you will see a ‘autoload.php’ file as well. You just need to require/include this class to using ‘monolog/monolog’.

 

require 'vendor/autoload.php';

 

Now you can easily access the ‘monolog/monolog’ classes in your project. Here I am writing a sample code so you can get some idea.

$log = new MonologLogger('name');

$log->pushHandler(new MonologHandlerStreamHandler('LOG_FILE_PATH/error.log', MonologLogger::WARNING));

$log->addWarning('Foo');

So these are very basic way to manage your project via Composer. To know the more details visit the composer official website https://getcomposer.org. I hope now you enjoy this tutorial and quite able to use composer. Best of luck for using Composer.

How to Change the Apache Port in XAMPP

Sometime it is necessary to change our apache server port number. It’s really important to now how to to that. It is quit easy  procedure, just follow the instruction.

STEP 1:  Go to your xampp(where you installed xampp) and then go “xamppapacheconf” and open the httpd.conf file.

STEP 2: You can see there

#Listen 0.0.0.0:80

#Listen [::]:80

Listen 80

 

Now you can edit the port number, Here is default is 80 enable, just change the number with your necessary port number.

 NB: “#” sign means disable sign, so you can simple disable port number 80 just add a # before the word Listen. And add your number by type Listen and your necessary port number.

STEP 3: Finally restart the xampp. This is the simple process it will take maximum 5 min.