1 | <?php |
||
15 | class TwigExtension extends \Twig_Extension |
||
16 | { |
||
17 | /** |
||
18 | * @var Router |
||
19 | */ |
||
20 | private $router; |
||
21 | |||
22 | /** |
||
23 | * @var FragmentHandler |
||
24 | */ |
||
25 | private $handler; |
||
26 | |||
27 | /** |
||
28 | * @var WidgetsContainer |
||
29 | */ |
||
30 | private $widgets; |
||
31 | |||
32 | /** |
||
33 | * @param Router $router |
||
34 | * @param FragmentHandler $handler |
||
35 | * @param WidgetsContainer $widgets |
||
36 | */ |
||
37 | public function __construct(Router $router, FragmentHandler $handler, WidgetsContainer $widgets) |
||
38 | { |
||
39 | $this->router = $router; |
||
40 | $this->handler = $handler; |
||
41 | $this->widgets = $widgets; |
||
42 | } |
||
43 | |||
44 | /** |
||
45 | * @return array |
||
46 | */ |
||
47 | public function getFilters() |
||
48 | { |
||
49 | return [ |
||
|
|||
50 | 'favicon' => new \Twig_SimpleFilter('favicon', [$this, 'favicon']), |
||
51 | ]; |
||
52 | } |
||
53 | |||
54 | /** |
||
55 | * @return array |
||
56 | */ |
||
57 | public function getFunctions() |
||
58 | { |
||
59 | return [ |
||
60 | 'widgets' => new \Twig_SimpleFunction('widgets', [$this, 'widgets'], ['is_safe' => ['html']]), |
||
61 | ]; |
||
62 | } |
||
63 | |||
64 | /** |
||
65 | * @param string $url |
||
66 | * |
||
67 | * @return string|false |
||
68 | */ |
||
69 | public function favicon($url) |
||
73 | |||
74 | /** |
||
75 | * @param string $place |
||
76 | * @param array $attributes |
||
77 | * @param array $options |
||
78 | * |
||
79 | * @return string |
||
80 | */ |
||
81 | public function widgets($place, array $attributes = [], array $options = []) |
||
94 | |||
95 | /** |
||
96 | * @return string |
||
97 | */ |
||
98 | public function getName() |
||
102 | } |
||
103 |
If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.
Let’s take a look at an example:
Our function
my_function
expects aPost
object, and outputs the author of the post. The base classPost
returns a simple string and outputting a simple string will work just fine. However, the child classBlogPost
which is a sub-type ofPost
instead decided to return anobject
, and is therefore violating the SOLID principles. If aBlogPost
were passed tomy_function
, PHP would not complain, but ultimately fail when executing thestrtoupper
call in its body.