S
S
simonnidze2015-09-04 18:28:05
PHP
simonnidze, 2015-09-04 18:28:05

ZF2 how to use the same set of functions in different controllers?

Hello! I am writing a Cats module in Zend Framework 2, which will allow editing and displaying information about cats.
I use Doctrine as an ORM.
Each cat has a relationship cat id->father id, cat id->mother id.
There is a method for building a pedigree:
private function createPedigreeArray($config){}
There are also two methods

private function getFatherInfo(){}
private function getMotherInfo(){}

These methods are auxiliary to the createPedigreeArray method,
all these 3 methods are written in the controller code, they are used to form arrays
$objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');

and pull data from different Entities.
Everything is working.
In the future, I would like to use the createPedigreeArray() function to generate a pedigree in another controller.
For example, I will have an okat (like litter only for cats), the okata table will have two parent IDs, and I would like to use the same createPedigreeArray() function by simply adding one condition to it.
But the formation of the Okata family tree will occur exactly in another controller, if not in another module.
What is the best way to use it in order to achieve the desired result in the future?
I’m also wondering if you should even write your own methods in the controller, other than action, but which will be called only in the action context of this controller, or is it also better to take them out? If rendered, is there a best practice for this?
I'm new to ZF2, I'm actively studying it and I really like it.
Leafing through the manual, I realized that you can write your own controller plugin, which can be called from different controllers.
I will be glad to any advice. Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2015-09-04
Protko @Fesor

the same set of functions in different controllers?

take it out to the service, register it in the dependency container, and rejoice.

D
Dmitry Marinov, 2016-09-18
@felessar

Well, here you can do it differently.
Take out everything that is not actionin the service and connect it (as mentioned in the previous comment) through Dependency Injection.
You can, of course, write a trait and define the same set of functions there or expand AbstractActionControllerit, but it seems to me that the service is better.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question