• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • 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

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Development / PHP Dependency Injection With Pimple

PHP Dependency Injection With Pimple

April 28, 2014 by Rana Ahsan Leave a Comment

Dependency Injection PHP

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 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Development Tagged With: php

About Rana Ahsan

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

Reader Interactions

Leave a ReplyCancel reply

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

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • Control HTML5 Audio With Jquery
    Control HTML5 Audio With Jquery
  • How To Work With Codeigniter Caching In PHP
    How To Work With Codeigniter Caching In PHP
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Popular Tutorials

  • How To Work With C# Serial Port Communication
  • PHP HTML5 Video Streaming Tutorial
  • Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
  • How To Work With JSON In Node.js / JavaScript
  • Control HTML5 Audio With Jquery
  • How To Work With Codeigniter Caching In PHP
  • Get Facebook C# Api Access Token
  • Utilizing Config File In C#.NET Application
  • Generate HTTP Requests using c#

Recent Tutorials

  • Building Auth With JWT – Part 2
  • 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

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023