venne / generics
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
Requires
- php: >=5.3.1
- nette/nette: ~2.0
Requires (Dev)
- nette/tester: ~1.0.0
This package is auto-updated.
Last update: 2024-10-29 04:47:35 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();