Maybe it's a trivial question but I'm beginner with Silex and I don't know how to do it...so here is my situation :
I have a Silex app, everything works but I'm not a big fan of my Controller because there is a lot of code and I reapeat this code two times :
First controller :
$app->match('/', function (Request $request) use ($app) {
// 1/ I get data from a form
// 2/ I check if User is logged
// 2.1 / If not logged -> I created new User (Entity User) + send email
// 3/ I create a new Event (Entity Event) + put some file on AWS s3
// 4/ I create a new Product (Entity Product)
// 5/ I activate some add-on to my Event (request to an other BDD)
return $app['twig']->render('home.html.twig');
})->bind('home');
Second controller
$app->match('/manage-my-product', function (Request $request) use ($app) {
if ($app['security.authorization_checker']->isGranted('IS_AUTHENTICATED_FULLY')) {
// 1/ I get data from a form
// 2/ If user is here he must be logged so no need to check one more time
// 3/ I create a new Event (Entity Event) + put some file on AWS s3
// 4/ I create a new Product (Entity Product)
// 5/ I activate some add-on to my Event (request to an other BDD)
} else {
return $app->redirect($app["url_generator"]->generate("login"));
}
})->bind('product');
As you can see I do almost the same with few difference, so my question : Is to possible to put that logic outside the Controller and use it twice? How should I put that logic outside my Controller?
I don't really know how to do it because I have lot of different things inside :
Class Name
with the attributes + getter / setter, one Class NameDAO
where I have all my methods (findByEmail($email), find($id), ...
) that extends an abstract DAO class
(my database connection + one abstract method to return a Class Name
)Class NameDAO
have a dedicated service (eg. $app['dao.user']
)EDIT :
According to the anwser I get I think my question wasn't very clear about my real problem...I had the intuition I need to use Service but I have trouble to build it so :
As I said before, I already have services $app['user.dao']
and $app['event.dao']
for example that I use to create a new User or a new Event for example, so should I do :
$app->match('/', function (Request $request) use ($app) {
// 1/ Service 1 to create new user
// 2/ Service 2 to create new event
// 3/ Service 3 to create new add-on
// and so on...
return $app['twig']->render('home.html.twig');
})->bind('home');
OR
$app->match('/', function (Request $request) use ($app) {
// Use ONE big service that use all the services I need
return $app['twig']->render('home.html.twig');
})->bind('home');
END EDIT
As I said it works right now, but I'd like to know if it's possible to mix all this inside one method / function / service that I could use multiple time, could be nice for my future app !
Thanks
You can use Services which you add to the Service Container as documented here:
(check the Symfony version that you are using)