There is no license information available for the latest version (dev-master) of this package.

Generics in PHP

dev-master 2014-03-11 09:56 UTC

This package is auto-updated.

Last update: 2023-03-29 00:41:50 UTC



Basic usage

Use phpDoc @template as definition of template types:

 * @template IEntity
class Repository {

	public function save(IEntity $entity)


Now you can generate own class generated from template. Symbol _ is default separator between class name and template type.

class Article {}

$articleRepository = new Repository_Article;
$articleRepository->save(new Article); // works
$articleRepository->save(11); // fail

If you need to use multiple template types, define them in phpDoc:

 * @template IEntity, IEntityManager

and work with it similarly:

$articleRepository = new Repository_Article_EntityManager;

If you want to remove typehint:

$repository = new Repository_;
$repository->save('yeah'); // works
$repository->save(33); // works
$repository->save(new stdClass()); // works

Working with namespaces

Use absolute class names:

$article = new App\Article;
$article->text = 'Foo';

$articleRepository = new App\Repository_App\Article;

Or you can use use statements:

use App\Article;
use App\Repository_App\Article as ArticleRepository;

$article = new Article;
$article->text = 'Foo';

$articleRepository = new ArticleRepository;


	- ArticleRepository_Article
	- ArticleService
use ArticleRepository_Article as ArticleRepository;

class ArticleService {

	private $repository;

	public function __construct(ArticleRepository $repository)
		$this->repository = $repository;


Inheritance rules

abstract class Entity {}
class Page extends Entity {}
class Article extends Page {}
abstract class Repository {}

/** @template Page */
class PageRepository extends Repository {
	public function(Page $entity) {}

$pageRepository = new PageRepository;
$articleRepository = new PageRepository_Article;

echo $pageRepository instanceof Repository; // TRUE
echo $pageRepository instanceof PageRepository; // TRUE

echo $articleRepository instanceof Repository; // TRUE
echo $articleRepository instanceof PageRepository; // FALSE


composer require venne/generics

Configuration in Nette framework

	generics: Venne\Generics\DI\GenericsExtension
	separator: '_'

Manual configuration

$generics = new Venne\Generics\Generics;
$loader = new Venne\Generics\Loader($generics);