PHP code example of aeviiq / factory

1. Go to this page and download the library: Download aeviiq/factory library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

aeviiq / factory example snippets


// src/Kernel.php
namespace App;

use Aeviiq\Factory\FactoryCompilerPass;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;

class Kernel extends BaseKernel
{
    use MicroKernelTrait;

    // ...

    protected function build(ContainerBuilder $container): void
    {
        $container->addCompilerPass(new FactoryCompilerPass());
    }
}

// src/AppBundle/AppBundle.php
namespace AppBundle;

use Aeviiq\Factory\FactoryCompilerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class AppBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new FactoryCompilerPass());
    }
}

final class EncoderFactory extends AbstractServiceFactory
{
    public function getEncoder(User $user): Encoder
    {
        // getOneBy ensures 1, and only 1 encoder is returned. 
        // In case multiple encoders (or none) are found, a LogicException will be thrown.
        // In case the result is optional, you could use the getOneOrNullBy().
        return $this->getOneBy(static function (Encoder $encoder) use ($user) {
            return $encoder->supports($user);
        });
    }

    protected function getTargetInterface(): string
    {
        // All services with this interface will automatically be wired to the factory 
        // without needing any additional service configuration.
        // Using autowire these few lines are all you would need to implement your factory.
        return Encoder::class;
    }
}

final class Foo
{
    /**
     * @var FactoryInterface
     */
    private $encoderFactory;

    public function __construct(FactoryInterface $encoderFactory)
    {
        $this->encoderFactory = $encoderFactory;
    }

    public function authenticateUser(User $user): void
    {
        // ...
        $encoder = $this->encoderFactory->getEncoder($user);
        if (!$encoder->isValidPassword($user->getPassword, $presentedPassword, $user->getSalt())) {
            // ...
        }
        // ...
        
    }
}