M
M
Mike Evstropov2016-06-02 13:46:08
symfony
Mike Evstropov, 2016-06-02 13:46:08

How to remove part of the logic from the controller?

For example, we have a main page, which will contain different blocks (search, articles, registration, etc). Of course, the blocks will be repeated in other controllers. I need to somehow transfer the formation of variables / arrays passed to the template to generate these blocks into separate controllers (or other entities that I don't know). What I tried to do:
Create MainController

<?php
// /src/AppBundle/Controller/MainController.php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class MainController extends Controller {
  /**
     * @Route("/", name="main")
     */
  public function mainAction () {
    $filter_form = $this->forward( 'app.test:testAction' );
    return new Response ( json_encode(Array( 'filter_form' => $filter_form )) );
  }
}

We are trying to move the formation of the string to another "service", called TestController.
# app/config/services.yml
services: app.test: class: AppBundle\Controller\TestController

We create a TestController controller that should return a string.
<?php
// /src/AppBundle/Controller/TestController.php
namespace AppBundle\Controller;
class TestController {
  public function testAction () {
    return 'STRING';
  }
}

But TestController returns a Response object, and in the output we see:
{"filter_form":{"headers":{}}}
And I'm
{"filter_form":"STRING"}
just starting to understand the framework. Tell me how to make the controller return what is passed to the return statement. Or how to do it right so as not to duplicate the code for the controllers (that is, take the logic out of the MainController)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Soshnikov, 2016-06-02
@Aroused

1. Create a service class mySuperManager
2. Push all the logic into it
3. In the controller, ask mySuperManager to give the necessary data and pass them to the view or json or somewhere else)
Controller example:
An example of the mySuperService class method
In my case, mySuperManager immediately returns json, but in your situation, return what you need: an object, an array, a string, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question