Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7743039
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T09:25:50+00:00 2026-06-01T09:25:50+00:00

I have recently started reading about dependency injection and it has made me rethink

  • 0

I have recently started reading about dependency injection and it has made me rethink some of my designs.

The problem i have is something like this:
Let’s say i have two classes: Car and Passenger;
For those two classes i have some data mappers to work with the database: CarDataMapper and PassengerDataMapper

I want to be able to do something like this in code:

$car = CarDataMapper->getCarById(23); // returns the car object
foreach($car->getPassengers() as $passenger){ // returns all passengers of that car
    $passenger->doSomething();
}

Before I knew anything about DI, I would build my classes like this:

class Car {
    private $_id;
    private $_passengers = null;

    public function getPassengers(){
        if($this->_passengers === null){
            $passengerDataMapper = new PassengerDataMapper;
            $passengers = $passengerDataMapper->getPassengersByCarId($this->getId());
            $this->setPassengers($passengers);
        }
        return $this->_passengers;  
    }

}

I would also have similar code in the Passenger->getCar() method to fetch the car the passenger is in.

I now understand that this creates dependencies (well, I understood it before too, but I wasn’t aware that this is “wrong”) between the Car and the Passenger objects and the data mapper objects.

While trying to think of the solution for this two options came to mind, but I don’t really like any of them:

1: Doing something like this:

$car = $carDataMapper->getCarById(23);
$passengers = $passengerDataMapper->getPassengersByCarId($car->getId());
$car->setPassengers($passengers);

foreach($car->getPassengers() as $passenger){
    $passenger->doSomething();
}

But what if passengers have objects that they need injected, and what if the nesting goes to ten or twenty levels… I would wind up instantiating nearly every object in the start of my application, which would in turn query the entire database during the process.
If i have to send the passenger to another object which has to do something with the objects that the passenger holds, I do not want to immediately instantiate these objects too.

2: Injecting the data mappers into the car and passenger objects and having something like this:

class Car {
    private $_id;
    private $_passengers = null;
    private $_dataMapper = null;

    public function __construct($dataMapper){
        $this->setDataMapper($dataMapper);
    }

    public function getPassengers(){
        if($this->_passengers === null && $this->_dataMapper instanceof PassengerDataMapper){
            $passengers = $this->_dataMapper->getPassengersByCarId($this->getId());
            $this->setPassengers($passengers);
        }
        return $this->_passengers;  
    }
}

I dont like this any better, because it’s not like the Car is really unaware of the data mapper, and without the data mapper, the Car could behave unpredictably (not returning passengers, when it actually has them)

So my first question is:
Am I taking a completely wrong approach here, because, the more I look at it, the more it looks like I’m building an ORM, instead of a business layer?

The second question is:
is there a way of actually decoupling the objects and the data mappers in a way that would allow me to use the objects as described in the very first code block?

Third question:
I’ve seen some answers for other languages (some version of C, I think) resolving this issue with something like this described here:
What is the proper way to inject a data access dependency for lazy loading?
As I haven’t had time to play with other languages, this makes no sense to me, so I’d be grateful if someone would explain the examples in the link in PHP-ish.

I have also looked at some DI frameworks, and read about DI Containers and Inversion of Control, but from what I understood they are used to define and inject dependencies for ‘non dynamic’ classes, where for instance, the Car would depend on the Engine, but it would not need the engine to be loaded dynamically from the db, it would simply be instantiated and injected into the Car.

Sorry for the lengthy post and thanks in advance.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T09:25:52+00:00Added an answer on June 1, 2026 at 9:25 am

    I was going to say “I know this is an old question but…” then I realized you posted it 9 hours ago, which is cool, because I just came to a satisfactory ‘resolution’ for myself. I thought of the implementation and then I realized it is what people were calling ‘dependency injection’.

    Here is an example:

    class Ticket {
    
        private $__replies;
        private $__replyFetcher;
        private $__replyCallback;
        private $__replyArgs;
    
        public function setReplyFetcher(&$instance, $callback, array $args) {
            if (!is_object($instance))
                throw new Exception ('blah');
            if (!is_string($callback))
                throw new Exception ('blah');
            if (!is_array($args) || empty($args))
                throw new Exception ('blah');
            $this->__replyFetcher = $instance;
            $this->__replyCallback = $callback;
            $this->__replyArgs = $args;
            return $this;
        }
    
        public function getReplies () {
            if (!is_object($this->__replyFetcher)) throw new Exception ('Fetcher not set');
            return call_user_func_array(array($this->__replyFetcher,$this->__replyCallback),$this->__replyArgs);
        }
    
    }
    

    Then, in your service layer (where you ‘coordinate’ actions between multiple mappers and models) you can call the ‘setReplyFetcher’ method on all of the ticket objects before you return them to whatever is invoking the service layer — OR — you could do something very similar with each mapper, by giving the mapper a private ‘fetcherInstance’ and ‘callback’ property for each mapper the object is going to need, and then set THAT up in the service layer, then the mapper will take care of preparing the objects. I am still weighing the differences between the two approaches.

    Example of coordinating in the service layer:

    class Some_Service_Class {
        private $__mapper;
        private $__otherMapper;
        public function __construct() {
            $this->__mapper = new Some_Mapper();
            $this->__otherMapper = new Some_Other_Mapper();
        }
        public function getObjects() {
            $objects = $this->__mapper->fetchObjects();
            foreach ($objects as &$object) {
                $object->setDependentObjectFetcher($this->__otherMapper,'fetchDependents',array($object->getId()));
            }
            return $objects;
        }
    }
    

    Either way you go, the object classes are independent of mapper classes, and mapper classes are independent of each other.

    EDIT: Here is an example of the other way to do it:

    class Some_Service {
        private $__mapper;
        private $__otherMapper;
        public function __construct(){
            $this->__mapper = new Some_Mapper();
            $this->__otherMapper = new Some_Other_Mapper();
            $this->__mapper->setDependentFetcher($this->__otherMapper,'someCallback');
        }
        public function fetchObjects () {
            return $this->__mapper->fetchObjects();
        }        
    }
    
    class Some_Mapper {
        private $__dependentMapper;
        private $__dependentCallback;
        public function __construct ( $mapper, $callback ) {
            if (!is_object($mapper) || !is_string($callback)) throw new Exception ('message');
            $this->__dependentMapper = $mapper;
            $this->__dependentCallback = $callback;
            return $this;
        }
        public function fetchObjects() {
            //Some database logic here, returns $results
            $args[0] = &$this->__dependentMapper;
            $args[1] = &$this->__dependentCallback;
            foreach ($results as $result) {
                // Do your mapping logic here, assigning values to properties of $object
                $args[2] = $object->getId();
                $objects[] = call_user_func_array(array($object,'setDependentFetcher'),$args)
            }
        }
    }
    

    As you can see, the mapper requires the other resources to be available to even be instantiated. As you can also see, with this method you are kind of limited to calling mapper functions with object ids as parameters. I’m sure with some sitting down and thinking there is an elegant solution to incorporate other parameters, say fetching ‘open’ tickets versus ‘closed’ tickets belonging to a department object.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have recently started reading up on Grails and would like to use SQL
I have recently started reading about Java EE6 and in the examples I follow
I have recently started seeing user agents like Java/1.6.0_14 (and variations) on my site
Hi I recently started experimenting with python currently reading Think like a computer scientist:
I have recently started reading Programming Challenges book by S. Skiena and believe or
I have recently started working on a legacy application that has most of its
I have recently started having problems with TortoiseCVS, or more specifically with plink, the
I have recently started using Vim as my text editor and am currently working
I have recently started working on a very large C++ project that, after completing
I have recently started looking into Google Charts API for possible use within the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.