Jump to content

PHP composition


c_pattle

Recommended Posts

I'm having a bit of trouble using composition.  I have a function in a class that uses composition.  Here is that function. 

 

function emailDetails() {
	$this->to = "hello@example.com";
	$this->subject = "Login Details";
	$this->message = "Here are your login details";
	return new emailClass($this);
}

 

Then in the "emailClass" the __construct function looks like this. 

 

    function __construct(&$user){
        $this->user=&$user;
$this->to = $this->user->to;
$this->from = "someone@example.com";
$this->subject = $this->user->subject;
$this->message = $this->user->message;
    }

 

This all works fine but my problem is that I then can't use the "emailClass" on it's own because it requires an instance of a class to be passed to it in it's construct.  Is this a poor case of design on my part?

 

 

Link to comment
Share on other sites

Well, first, if you're using PHP 5 you don't need to pass the User instance by reference.  Objects are automatically passed by reference.

 

But, yeah, your design is messed up.  Your Email class shouldn't require a User to work, right?  Logically, email is a utility service.  It should be able to be used throughout your system.  This is one of the reasons why I suggested turning it into a static class (all methods marked as static) in your previous thread on this subject.

 

If you're determined to use composition, it makes more sense for the User to contain the Email.  Why?  Because it's the User which depends on the Email functionality being present.  Email is a component (hence composition) of the User.

Link to comment
Share on other sites

Your design is FUBAR! ;) You are assigning Email properties to your User. In DDD, when you have 2 objects that should work together, but passing either object to the other is awkward, use a Service. I'm not for the make all Email methods static approach as it creates a hard dependency between either User and Email or vice versa.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.