Search code examples
phpmodel-view-controllerzend-framework2

Creating a factory class?


I found this snippet of code:

class WebsitesTableFactory extends AbstractModelFactory
{
    public function __invoke(ContainerInterface $container)
    {
        $dbAdapter = $container->get('bc_db');
        $tableGateway = $this->initializeTableGateway('websites', $dbAdapter, null, $container->get(Websites::class));
        return new WebsitesTable($tableGateway);
    }
}

What I have been used to is:

  • implementing the FactoryInterface instead of extending AbstractModelFactory
  • using ServiceLocatorInterface as a parameter for the createService function

How is this different from that implementation?

And what does the ::class mean?

Zend Version is 2.5.


Solution

  • PHP Class Constants

    ::class returns the FQCN (Fully Qualified Class Name), e.g. "\Namespace\Path\To\Classname".


    ZF2 - 3 Factories

    In preparation for ZF3 it became common to use __invoke(ContainerInterface $container) instead of createService(ServiceLocatorInterface $serviceManager).

    It was used as the default Factory you're used to was replaced with another that implements another Interface, though leaves room for the transition of ZF2 to ZF3.

    A standard Factory class in ZF3 looks like this:

    use Zend\ServiceManager\Factory\FactoryInterface;
    
    class DemoFactory implements FactoryInterface
    {
        public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
        {
            // Do your thing
        }
    }
    

    Note: a different FactoryInterface use-statement than in ZF2!


    Upgrade everything

    Clearly you're still using ZF2. I can strongly recommend you upgrade (or start upgrading) to ZF3. You could read the migration guide, however I would suggest you simply update everything in a single fell swoop.

    My suggestion would cause you a great deal of work (probably, depending on the size of your application) but everything would be up-to-date.

    I recommend going into your composer.json and removing all version constraints, then update everything with a composer update to the latest versions. Then go from there, you'll have endless errors to fix because of outdated stuff.

    (There might be exceptions of packages that cannot be upgraded, for whatever reason, please note they might cause unintended version constraints if you do follow the above advice).


    You might need help

    On the other hand is the thing that you don't know about ::class returning a FQCN, which is pretty basic and standard to use and has been for quite some time (since PHP 5.6 (released halfway 2014) if memory serves). As such, the above might be too overwhelming and I would recommend you seek help from a colleague or someone with more experience with Zend Framework development.