PHP code example of consistence-community / consistence-doctrine

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

    

consistence-community / consistence-doctrine example snippets




namespace Consistence\Doctrine\Example\User;

class Sex extends \Consistence\Enum\Enum
{

	public const FEMALE = 'female';
	public const MALE = 'male';

}



namespace Consistence\Doctrine\Example\User;

use Consistence\Doctrine\Enum\EnumAnnotation as Enum;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity()
 */
class User extends \Consistence\ObjectPrototype
{

	// ...

	/**
	 * @Enum(class=Sex::class)
	 * @ORM\Column(type="string_enum", nullable=true)
	 * @var \Consistence\Doctrine\Example\User\Sex|null
	 */
	private $sex;

	// ...

	public function __construct(
		// ...
		Sex $sex = null
		// ...
	)
	{
		// ...
		$this->sex = $sex;
		// ...
	}

	// ...

}



namespace Consistence\Doctrine\Example\User;

$user = new User(
	// ...
	Sex::get(Sex::FEMALE)
	// ...
);
/** @var \Doctrine\ORM\EntityManager $entityManager */
$entityManager->persist($user);

// when persisting User::$sex to database, `female` will be saved
$entityManager->flush();



namespace Consistence\Doctrine\Example\User;

/** @var \Doctrine\ORM\EntityManager $entityManager */
$user = $entityManager->find(User::class, 1);
var_dump($user->getSex());

/*

class Consistence\Doctrine\Example\User\Sex#5740 (1) {
  private $value =>
  string(6) "female"
}

*/



use Consistence\Doctrine\Enum\Type\BooleanEnumType;
use Consistence\Doctrine\Enum\Type\FloatEnumType;
use Consistence\Doctrine\Enum\Type\IntegerEnumType;
use Consistence\Doctrine\Enum\Type\StringEnumType;

use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\DBAL\Types\Type as DoctrineType;

// path to your Composer autoload file
$loader = ass); // float_enum
DoctrineType::addType(IntegerEnumType::NAME, IntegerEnumType::class); // integer_enum
DoctrineType::addType(StringEnumType::NAME, StringEnumType::class); // string_enum



use Consistence\Doctrine\Enum\EnumPostLoadEntityListener;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\ORM\Events;

/** @var \Doctrine\ORM\EntityManager $entityManager */
/** @var \Doctrine\ORM\Mapping\Driver\AnnotationDriver $annotationDriver */
$annotationDriver = $entityManager->getConfiguration()->getMetadataDriverImpl();
$annotationReader = $annotationDriver->getReader();

// make sure to use the most appropriate cache for given environment to get the best performance
$cache = new ArrayCache();

$entityManager->getEventManager()->addEventListener(
	Events::postLoad,
	new EnumPostLoadEntityListener($annotationReader, $cache)
);