CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact
Home Development PHP Dependency Injection With Pimple

PHP Dependency Injection With Pimple

Rana Ahsan April 28, 2014 Leave a Comment


 PHP Dependency Injection With Pimple    

Injecting dependencies to our core application is an everyday requirements/needs and thus is a most commonly used design patterns. Composer already made our live easier by managing library dependencies for PHP applications. Today, I will introduce you with the best way of PHP dependency injection into a web application with using very simple and slim Pimple library. This article might rather be treated as tip/tricks better than a tutorial.

Lets Start With A Simple Approach:

Now, what about initiating various object instances that we will be using on our project? yes, sure we may do this by simply initiating all required objects in a bootstrap file and save them in a global variable and use from there wherever needed, such as below:

$libs = array();
$libs["cache"] =  new CacheObject();
$libs["orm"] =  new ORM();
$libs["logger"] =  new Logger();
//....so on

What Is The Problem With This Implementation?

Well, apparently nothing. But, the problems come along the way, when we are developing a comparatively larger application which manages a lot of dependencies, but not all requests use all dependencies. As you can notice, the above approach will initiate all dependencies unnecessarily even if they doesn’t need to. This will result higher memory consumption on server and also request processing performance impact as well.

Can’t Lazy Loading Already solved this?

If you know about lazy loading with PHP closure, then you will might wonder why we need another library when we can already do it. Yes, its true, its possible to do it without this library, but this library will just simplify the usage one step more along with other features. Such as, to use a lazy loaded object with that approach, you will have to write as below:

$log = $app["logger"]();
$log->addMessage("DEBUG", "Test Log message");

but if the initialization was with using Pimple, we could simple use

$app["logger"]->addMessage("DEBUG", "Test Log message");

Why Use Pimple For PHP Dependency Injection?

I will recommend using pimple because it is made to make the above process super simple and easy to use. To use pimple, you won’t have to do much, but in return you will get several things done:

$libs = Pimple();
$libs["cache"] = function() {  return new CacheObject();};
$libs["orm"] =  function() {  return new ORM();};
$libs["logger"] =  function() {  return new Logger();};
//....so on

That’s It?

Not really, there are some other useful features as well.

with using protect() method, you can tell pimple to define the anonymous function as parameter value instead of usual service definition.

Also, generally pimple if made to return the same instance. To change the behavior, if you want factory like behavior, it provides factory() method to wrap around the anonymous function and do the job.

Read the official documentation, which shows the usage nicely with examples.

Hope this simple PHP dependency injection tips will help in some scenario. If you have any questions about any use cae/feedback, I will love to hear it. Happy coding 🙂

Related

Filed Under: Development Tagged With: php

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
  • Facebook C# API Tutorials
  • LinQ To SQL Database Update Operations In C#
  • Tutorial On Uploading File With CodeIgniter Framework / PHP
  • Utilizing Config File In C#.NET Application
  • Using Supervisord Web Interface And Plugin
  • Using GIT Plugin For Netbeans IDE

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • S. Chalisque on PHP HTML5 Video Streaming Tutorial
  • Armorik on Generate HTTP Requests using c#
  • iswaps on PHP HTML5 Video Streaming Tutorial
  • TAKONDWA on PHP HTML5 Video Streaming Tutorial
  • rorenzo on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2022 · CodeSamplez.com ·

Copyright © 2022 · Streamline Pro Theme on Genesis Framework · WordPress · Log in