开发者

what is factory in php and how it can be useful? [closed]

开发者 https://www.devze.com 2022-12-25 04:25 出处:网络
Closed. This question needs to be more focused. It is not currently accepting answers. 开发者_StackOverflow中文版Want to improve this question? Update the question so it focuses on one pro
Closed. This question needs to be more focused. It is not currently accepting answers.
开发者_StackOverflow中文版

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 7 years ago.

Improve this question

I just want to know that what is the factory in PHP and how can I use it in my code?

Are there and benefits and drawbacks of it?


An AbstractFactory is a Creational Design Pattern, that

Provides an interface for creating families of related or dependent objects without specifying their concrete classes.

In a nutshell:

class MercedesFactory
{
    public static function createCar()
    {
        $engine = new MercedesEngine;
        $car = new Mercedes($engine);
        return $car;
    }
}
  • AbstractFactory Example in PHP Code 1
  • AbstractFactory Example in PHP Code 2

There is also the Factory Method, which

Defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

In a nutshell:

class User
{
    public static function create()
    {
        return new self;
    }
}
  • Factory Method Example in PHP Code


Factory is one of the most useful patterns, because it provides a way to remove specific class names from the code, making it easier to support and refactor.

Consider an example: you've got an application that sends emails and uses 'Mailer' class for this purpose:

class Site

  function sendWelcomeMail
     $m = new Mailer;
     $m->send("Welcome..."); 

  function sendReminderMail
     $m = new Mailer;
     $m->send("Reminder..."); 

 etc...

One day you decide to use another mailer class, called 'NewMailer'. With code like above you have to find all occurences of Mailer and replace them manually into NewMailer. This can be a real pain in a large project.

With a Factory you don't use 'new' and specific class names and just call a method when you need an object

class Factory

      function createMailer() 
          return new Mailer;


class Site

  function sendWelcomeMail
     $m = Factory::createMailer();
     $m->send("Welcome..."); 

  function sendReminderMail
     $m = Factory::createMailer();
     $m->send("Reminder..."); 

 etc...

To replace Mailer with NewMailer all over the place you just change one single line in the factory method.


It's a function that creates classes. If you need to bulk-create classes with minor variations in behavior then it's useful. On the other hand, abuse leads to things like FactoryFactoryFactoryFactoryFactoryFactory.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号