venne / generics
Generics in PHP
Installs: 8
Dependents: 0
Suggesters: 0
Security: 0
Stars: 2
Watchers: 2
Forks: 0
Open Issues: 0
pkg:composer/venne/generics
Requires
- php: >=5.3.1
- nette/nette: ~2.0
Requires (Dev)
- nette/tester: ~1.0.0
This package is auto-updated.
Last update: 2025-09-29 01:43:22 UTC
README
Usage
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; $articleRepository->save($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->save($article);
Autowiring
services: - 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
Installation
composer require venne/generics
Configuration in Nette framework
extensions: generics: Venne\Generics\DI\GenericsExtension
generics: separator: '_'
Manual configuration
$generics = new Venne\Generics\Generics; $loader = new Venne\Generics\Loader($generics); $loader->register();