PHP code example of mooti / factory

1. Go to this page and download the library: Download mooti/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/ */

    

mooti / factory example snippets




namespace My;

class Foo
{
	private $firstName;
	private $lastName;

	public function __construct($firstName, $lastName) {
		$this->firstName = $firstName;
		$this->lastName  = $lastName;
	}

	public function hello()
	{
		return 'hello '.$this->firstName. ' ' . $this->lastName;
	}
}




namespace Your;

use Mooti\Factory\Factory;
use My\Foo;

class Bar
{
	use Factory;

	public function speak($firstName, $lastName)
	{
		$foo = $this->createNew(Foo::class, $firstName, $lastName);
		return $foo->hello();
	}
}


 = new \Your\Bar();
echo $bar->speak('Ken', 'Lalobo');



My\Foo;
use Your\Bar;

class BarTest extends \PHPUnit_Framework_TestCase
{
	/**
     * @test
     */
    public function speakSucceeds()
    {
    	$firstName = 'Ken';
    	$lastName  = 'Lalobo';
    	$greeting  = 'Hello Ken Lalobo';

        $foo = $this->getMockBuilder(Foo::class)
            ->disableOriginalConstructor()
            ->getMock();

        $foo->expects(self::once())
            ->method('hello')
            ->will(self::returnValue($greeting));

        $bar = $this->getMockBuilder(Bar::class)
            ->disableOriginalConstructor()
            ->setMethods(['createNew'])
            ->getMock();

        $bar->expects(self::once())
            ->method('createNew')
            ->with(
                self::equalTo(Foo::class),
                self::equalTo($firstName),
                self::equalTo($lastName)
            )
            ->will(self::returnValue($foo));

        self::assertSame($greeting, $bar->speak($firstName, $lastName));
    }
}


My\Foo;
use Your\Bar;

class BarTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function speakSucceeds()
    {
        $firstName = 'Ken';
        $lastName  = 'Lalobo';
        $greeting  = 'Hello Ken Lalobo';

        $foo = $this->getMockBuilder(Foo::class)
            ->disableOriginalConstructor()
            ->getMock();

        $foo->expects(self::once())
            ->method('hello')
            ->will(self::returnValue($greeting));

        $bar = new Bar;

        $bar->addInstance(Foo::class, $foo);

        self::assertSame($greeting, $bar->speak($firstName, $lastName));
    }
}

$ php bin/run.php
$ Hello Ken Lalobo