From f8e8a8dc2a2f1a331677171fb9dea52fc95aae4e Mon Sep 17 00:00:00 2001 From: Ivan Barlog Date: Tue, 24 Oct 2017 02:33:32 +0200 Subject: [PATCH] add BaseDataSource --- README.md | 43 +++++++++++++++++++++++++++++++ src/DataSource/BaseDataSource.php | 43 +++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 src/DataSource/BaseDataSource.php diff --git a/README.md b/README.md index 7cddc20..41cd7c7 100644 --- a/README.md +++ b/README.md @@ -231,6 +231,49 @@ class CustomForm extends AbstractType { } ``` +# Reusing data sources + +In order to reuse data source between for instance multiple tabs you can easily create Twig functions by extending our `BaseDataSource`. + +Simply add to your services.yml following statement: + +```yaml + AppBundle\DataProvider\: + resource: '../../src/AppBundle/DataProvider' + tags: ['twig.extension'] +``` + +You can specify any folder within your project you want. In this example we have chosen `AppBundle\DataProvider` namespace. + +Each class within this namespace which extends `Everlution\AjaxcomBundle\DataSource\BaseDataSource` is scanned for public methods with suffix `Provider` via reflexion and we are creating the simple Twig functions from these methods. Let's see the example: + + +```php +// AppBundle\DataProvider\Example.php + +// simple function which returns static array +public function navigationProvider() { + return [ + // some data... + ]; +} + +// you can use parametrical functions and injected services as well +public function userProfileProvider(int $id) { + return $this->someService->getData($id); +} +``` + +After creating such class you can simply call the function within twig: + +```twig +{{ dump(navigation()); }} {# will dump static array #} + +{% for item in userProfile(2) %} + {{ dump(item) }} +{% endfor %} +``` + # Best practice If you want to use AjaxcomBundle seamlessly you should copy `@EverlutionAjaxcom\layout_bootstrap_4.html.twig` to your project (eg. AppBundle) and modify it to your needs. diff --git a/src/DataSource/BaseDataSource.php b/src/DataSource/BaseDataSource.php new file mode 100644 index 0000000..f15e69f --- /dev/null +++ b/src/DataSource/BaseDataSource.php @@ -0,0 +1,43 @@ + + */ +class BaseDataSource extends \Twig_Extension +{ + protected const TWIG_FUNCTION_SUFFIX = 'Provider'; + + /** + * @return array + */ + public function getFunctions() + { + $functions = []; + $class = new \ReflectionClass(get_class($this)); + + if (self::class === $class->name) { + return $functions; + } + + foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { + if (false === ($offset = strpos($method->getName(), self::TWIG_FUNCTION_SUFFIX))) { + continue; + } + + $functions[] = $this->registerAsTwigFunction(substr($method->getName(), 0, $offset)); + } + + return $functions; + } + + private function registerAsTwigFunction(string $name): ?\Twig_SimpleFunction + { + return new \Twig_SimpleFunction($name, [$this, $name.self::TWIG_FUNCTION_SUFFIX]); + } +}