Categories
Code Area PHP Programming Tips and Tricks Tools and Technologies

Array Chunk based on Key Value in PHP

Sometimes programmer needs to chunk or grouping array based on the array key value. Look at the below code snippet, here I have a multidimensional array, and I want to group all same elements of each category.

OUTPUT:

array (
  'php' => 
  array (
    0 => 
    array (
      'category' => 'php',
      'post_id' => 100,
    ),
    1 => 
    array (
      'category' => 'php',
      'post_id' => 102,
    ),
    2 => 
    array (
      'category' => 'php',
      'post_id' => 104,
    ),
  ),
  'html' => 
  array (
    0 => 
    array (
      'category' => 'html',
      'post_id' => 101,
    ),
    1 => 
    array (
      'category' => 'html',
      'post_id' => 104,
    ),
  ),
  'js' => 
  array (
    0 => 
    array (
      'category' => 'js',
      'post_id' => 103,
    ),
  ),
)
Categories
CakePHP Career Code Area PHP Programming Tips and Tricks Tools and Technologies

CakePHP Auth Allow to Specific Actions of Specific Controllers

It’s a common problem to CakePHP developer to auth allow to specific actions of a specific controller. Especially to newbies developer of CakePHP. Honestly, it’s really easy but little tricky. So this article is for whom, who looking for CakePHP auth allow to specific actions of specific controllers.

Assume you have three controllers ClientsController.php, JobsController.php and HomeController.php. Now you want to access:

  • index() action from all controller
  • lists() action of  ClientsController.php controller
  • jobs() action of JobsController.php controller
  • home() action of HomeController.php controller

To accomplish this goal open AuthController.php file and add these following line.

public function beforeFilter(Event $event)
{
   $this->Auth->allow(array('index'));
}

 

Then open ClientsController.php file and add these following line.

public function beforeFilter(Event $event)
{
   parent::beforeFilter($event);
   $this->Auth->allow(array('lists'));
}

 

Then open JobsController.php file and add these following line.

public function beforeFilter(Event $event)
{
   parent::beforeFilter($event);
   $this->Auth->allow(array('jobs'));
}

 

Then open HomeController.php file and add these following line.

public function beforeFilter(Event $event)
{
   parent::beforeFilter($event);
   $this->Auth->allow(array('home'));
}

In this way, you can auth allow to specific actions of specific controllers.

Categories
AngularJS Career Code Area Java Script Tips and Tricks

Getting Query String Values Without a Hash in the URL

$location.search() returns empty? Angular does not remove the query before the hash bang in URL. According to AngularJS documentation,  hash bang URL format is:

http://example.com/#!/bar?baz=23

So if you have no hash bang in your URL (e.g. http://example.com/bar?baz=23), and try to get query string value, then you can use this snippet.

function getQueryParams(queryParam, url) 
{
        var pageUrl = url || window.location.search.substring(1);
        var urlVariables = pageUrl.split(/[&||?]/);
        var response = null;

        for (var i = 0; i < urlVariables.length; i += 1) {
            var param = urlVariables[i];
            var paramName = (param || '').split('=');

            if (paramName[0] === queryParam) {
                response = paramName[1];
            }
        }
        return response;
}
    
console.log(getQueryParams('baz', 'http://example.com/bar?baz=23'));

This code is also with pure JavaScript (withour AngularJS).

Categories
Career Java Script Tips and Tricks

Start Counting After Scroll on Specific Element

Sometimes it’s important to do some activities when a specific element is visible on the web page. So something needs to be trigger when that element is showing on the web page. Suppose you want to start counting after scroll on that specific element. Here is the code for that.

HTML CODE:
<div class="container">
  <h2 class="well well-lg" style="margin-top: 200px;">Scroll Down</h2>
  <h2 class="well well-lg" style="margin-top: 200px;">Scroll Down</h2>
  <div class="jumbotron text-center" style="margin-top: 200px;">
    <div class="container">
      <div class="col-lg-3">
        <h2>Total Sales</h2>
        <h1 class="counter">967</h1>
      </div>
      <div class="col-lg-3">
        <h2>Total Sales</h2>
        <h1 class="counter">967</h1>
      </div>
      <div class="col-lg-3">
        <h2>Total Sales</h2>
        <h1 class="counter">967</h1>
      </div>
      <div class="col-lg-3">
        <h2>Total Sales</h2>
        <h1 class="counter">967</h1>
      </div>
    </div>
  </div>
</div>
JAVASCRIPT CODE:
function isCounterElementVisible($element) {
  var topView = $(window).scrollTop();
  var botView = topView + $(window).height();
  var topElement = $element.offset().top;
  var botElement = topElement + $element.height();
  return ((botElement <= botView) && (topElement >= topView));
}

$(window).scroll(function() {
  $(".counter").each(function() {
    isOnView = isCounterElementVisible($(this));
    if (isOnView && !$(this).hasClass('visibled')) {
      $(this).addClass('visibled');
      $(this).prop('Counter', 0).animate({
        Counter: $(this).text()
      }, {
        duration: 3000,
        easing: 'swing',
        step: function(now) {
          $(this).text(Math.ceil(now));
        }
      });
    }
  });
});

See Demo:

Categories
PHP Programming Tips and Tricks Tools and Technologies

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.

Categories
Code Area PHP Tips and Tricks

Return Image as response by PHP

Return Image as response By PHP

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

Categories
AngularJS Code Area Java Script

Download and then Print PDF File in AngularJS

Sometime developer need to download PDF file and print that pdf document. Here I have shared a code snippet for download pdf then print that pdf using angularJS.

$scope.printPdf = function (uuid){
        $http({
            url : 'PDF_URL',
            method : 'GET',
            headers : {
                'Content-type' : 'application/pdf'
            },
            responseType : 'arraybuffer'
        }).success(function(data, status, headers, config) {
            var pdfFile = new Blob([ data ], {
                type : 'application/pdf'
            });
            var pdfUrl = URL.createObjectURL(pdfFile);
            var printwWindow = $window.open(pdfUrl);
            printwWindow.print();
        }).error(function(data, status, headers, config) {
            alert('Sorry, something went wrong')
        });
    };
<button ng-click="printPdf()" type="button" class="btn btn-primary">Print PDF</button>

With this simple sample code snippet, you can easily download & print pdf by using angularJS.

Categories
Code Area Java Script Programming

Add Decimal Point Automatically After a Number

Here I have given a small code snipped for making a number as currency format by javascript only. This snippet will automatically be adding extra zeros after the decimal point. Let’s see it

Categories
AngularJS Java Script Programming

Remove ngOptions Elements in AngularJS

With the passing time, AngularJS is getting popularity day by day. We all know AngularJS is the structured, most powerful and powerful front-end framework. But today I am not going to describe you about the AngularJS. But I am here to describe an easier & effective way to Remove ngOptions elements in AngularJS.

How to Remove ngOptions Elements in AngularJS

AngularJS provides a ng-options directive to display the options of selectlist. Here I use a categories array (array of object) for the selectlist. Every category object has (id, name, and is_active) keys and is_active true means Active category and is_active false means Inactive category.

Now, I want to display two selectlist, one if for active and another one for inactive. To do this I am using filter:{is_active: true} for active category’s selectlist and filter:{is_active: false} for inactive category’s selectlist.

With this filter, you can easily refine options base on your application needed. So developers can fell free to use is and make their code more maintainable and handy.

If you have any advice or query, please fell free to ask me.

Categories
Design Pattern PHP Programming

What is Dependency Injection in 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
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.