mardi 26 juin 2018

Search pattern $_POST

I'm searching best solution for situation like this:

I have $_POST request with many params.

In controller i have action like this:

class SearchController extends Controller
{
    /**
     * @Route("/search", name="search")
     */
    public function searchAction(SalonFacade $salonFacade, Request $request){
        $wanted = $salonFacade::convertRequestToWantedSalon($request);
        if($wanted->isValid()) {
            $salons = $salonFacade->findSalonsBy($wanted);
            dump($salons);
        }else{
            dump($wanted->getValidErrors());
        }
        return $this->render('test.html.twig',
            array()
        );
    }
}

As u can guess i convert $_POST request to object called WantedSalon

class SalonFacade
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function findSalonsBy(WantedSalon $wanted)
    {
        return $this->entityManager
            ->getRepository(Salon::class)
            ->findNearestSalons($wanted);
    }
    public static function convertRequestToWantedSalon(Request $request): WantedSalon
    {
        $post = $request->request;
        $wanted = new WantedSalon();

        $paramsKeyToSet = array('lat', 'lon', 'maxDistance', 'serviceCategories', 'datetime', 'name', 'minRating', 'maxRating');
        foreach ($paramsKeyToSet as $wantedKey) {
            $wanted->__set($wantedKey, $post->get($wantedKey));
        }
        return $wanted;
    }
}

But now i see that is not good solution because if i want to add new parameter to form which coming to controller by $_POST i need to change code in THREE places:

  1. add new field in WantedSalon object declaration
  2. add new parameter in SalonFacade::convertRequestToWantedSalon()
  3. i need to consider new field in declaration of SalonRepository->findNearestSalons()

Could you advice any better solution? Best regards

Aucun commentaire:

Enregistrer un commentaire