Model self instantiating via factory-like static methods

Posted 1 month ago by HectorOrdonez

I have never seen this practice before, and I am struggling to see the benefits. My intuition tells me it's a bad practice, but I might be biased.

I would like to know what you guys think about this.

Let's say I have a shop, and Product and Order models.

What about this, then:

class Order extends Model {
    public static function forProduct(Product $product)
    {
           $order = new Order();
           $order->setProductId($product->getId());
           $order->save();
           return $order;
    }
}

In my opinion models should not know how to build themselves, and I would definitely put that kind of logic in a repository. It just feels wrong. I also think this is not testable code.

What do you guys think?

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.