Search code examples
phpsymfonysymfony-3.2

Access Entity through Controller Symfony 3


For a school project, I need to develop a card game.

I'm working on the card deposit. All my cards are stored in a database, and when i deposit a card, I just send a form with the id of the card in an hidden form.

The problem is : How can I access the played card's properties through my Controller ? I've tested everything, and actually I can get them but I have to set all my Entity's property in public, which is really bad I think.

I really don't find how to do, maybe some help or tips could help me.

Here's my Controller's function :

/**
     * @Route("/poser/{partie}", name="poser_carte")
     */
    public function poserCarte(Request $request, Partie $partie){
        $cartePosee = $request->request->all();
        $cartePoseeTrait = $cartePosee['carte_id'];

        $em = $this->getDoctrine()->getManager();
        $carte = $em->getRepository('AppBundle:Cartes')->findById($cartePoseeTrait);

        var_dump($carte[0]->categorie);

        $tourde = $partie->getPartieTourJoueurId();
        var_dump($tourde);

        $joueur1 = $partie->getJoueur1Id()->getId();
        var_dump($joueur1);

        $joueur2 = $partie->getJoueur2Id()->getId();
        var_dump($joueur2);

        echo $cartePoseeTrait;

        if ($tourde == $joueur1){
            echo 'coucou joueur 1';
            $mainJ1 = json_decode($partie->getMainJoueur1());
            var_dump($mainJ1);
            //on supprime la valeur du tableau et on l'ajoute dans l'autre tableau correspondant.
        }
        elseif ($tourde == $joueur2){
            echo 'coucou joueur 2';
            $mainJ2 = json_decode($partie->getMainJoueur2());
        }
        else {
            echo 't\'as rien à faire ici !';
        }
    }

And here's my Card entity :

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * Cartes
 *
 * @ORM\Table(name="cartes")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CartesRepository")
 * @Vich\Uploadable
 */
class Cartes
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    public $id;

    /**
     * @var string
     *
     * @ORM\Column(name="categorie", type="string", length=255)
     */
    public $categorie;

    /**
     * @var string
     *
     * @ORM\Column(name="nom", type="string", length=255)
     */
    public $nom;

    /**
     * @var int
     *
     * @ORM\Column(name="valeur", type="integer")
     */
    public $valeur;

    /**
     * @var bool
     *
     * @ORM\Column(name="extra", type="boolean")
     */
    public $extra;

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     *
     * @Vich\UploadableField(mapping="carte_image", fileNameProperty="imageName")
     *
     * @var File
     */
    public $imageFile;

    /**
     * @ORM\Column(type="string", length=255)
     *
     * @var string
     */
    public $imageName;

    /**
     * @ORM\Column(type="datetime")
     *
     * @var \DateTime
     */
    public $updatedAt;


    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set categorie
     *
     * @param string $categorie
     *
     * @return Cartes
     */
    public function setCategorie($categorie)
    {
        $this->categorie = $categorie;

        return $this;
    }

    /**
     * Get categorie
     *
     * @return string
     */
    public function getCategorie()
    {
        return $this->categorie;
    }

    /**
     * Set nom
     *
     * @param string $nom
     *
     * @return Cartes
     */
    public function setNom($nom)
    {
        $this->nom = $nom;

        return $this;
    }

    /**
     * Get nom
     *
     * @return string
     */
    public function getNom()
    {
        return $this->nom;
    }

    /**
     * Set valeur
     *
     * @param integer $valeur
     *
     * @return Cartes
     */
    public function setValeur($valeur)
    {
        $this->valeur = $valeur;

        return $this;
    }

    /**
     * Get valeur
     *
     * @return int
     */
    public function getValeur()
    {
        return $this->valeur;
    }

    /**
     * Set image
     *
     * @param string $image
     *
     * @return Cartes
     */
    public function setImage($image)
    {
        $this->image = $image;

        return $this;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Set extra
     *
     * @param boolean $extra
     *
     * @return Cartes
     */
    public function setExtra($extra)
    {
        $this->extra = $extra;

        return $this;
    }

    /**
     * Get extra
     *
     * @return bool
     */
    public function getExtra()
    {
        return $this->extra;
    }

    /**
     * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
     * of 'UploadedFile' is injected into this setter to trigger the  update. If this
     * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
     * must be able to accept an instance of 'File' as the bundle will inject one here
     * during Doctrine hydration.
     *
     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
     *
     * @return Product
     */
    public function setImageFile(File $image = null)
    {
        $this->imageFile = $image;

        if ($image) {
            // It is required that at least one field changes if you are using doctrine
            // otherwise the event listeners won't be called and the file is lost
            $this->updatedAt = new \DateTimeImmutable();
        }

        return $this;
    }

    /**
     * @return File|null
     */
    public function getImageFile()
    {
        return $this->imageFile;
    }

    /**
     * @param string $imageName
     *
     * @return Product
     */
    public function setImageName($imageName)
    {
        $this->imageName = $imageName;

        return $this;
    }

    /**
     * @return string|null
     */
    public function getImageName()
    {
        return $this->imageName;
    }
}

I know it's certainly something very easy to do but I really don't find :(

Thank you for your help.


Solution

  • You should not (never?) set your entity's properties as public, this is why we have getters and setters.

    For example, this

        $carte = $em->getRepository('AppBundle:Cartes')->findById($cartePoseeTrait);
    
        var_dump($carte[0]->categorie);
    

    Should be (I assume the carte's id are unique)

        $carte = $em->getRepository('AppBundle:Cartes')->findOneById($cartePoseeTrait);
    
        var_dump($carte->getCategorie());// You call the getter of the categorie private
                                         // property $category
    

    Also don't forget to check that $carte is not null (or if you use findById) an empty array.

    Take a look at those docs :

    http://symfony.com/doc/current/doctrine.html#generating-getters-and-setters

    Or in french

    https://openclassrooms.com/courses/developpez-votre-site-web-avec-le-framework-symfony2/la-couche-metier-les-entites#/id/r-2080446

    http://www.apprendre-php.com/tutoriels/tutoriel-49-mthodes-magiques-set-et-get.html

    I'm not sure if this is the answer you wanted, but I hope it will help you :-)