Symfony non integra al suo interno componenti per lavorare con i databases, ma è integrato con la libreria di terze party ‘Doctrine’.
Possiamo trovare le librerie in Sources Files/vendor/doctrine
1. Aprire app/config/parameters.yml, questi sono i dati di accesso al DB, sono stati creati in fase di creazione del progetto
1 2 3 4 5 6 7 | # app/config/parameters.yml parameters: database_host: localhost database_name: test_project database_user: root database_password: |
2. Aprire app/config/config.yml, qui settiamo i parametri per la corretta scrittura e charset che DEVE essere utf8mb4
utf8mb4 è stata introdotta dalla versione 5.5.3
Il vecchio utf8 usa al massimo 3 bytes, utf8mb4 usa al massimo 4 bytes per carattere, supportando quindi un maggior numero di caratteri.
1 2 3 4 5 6 7 | doctrine: dbal: ... charset: utf8mb4 default_table_options: charset: utf8mb4 collate: utf8mb4_unicode_ci |
3. Creiamo il DB da phpMyAdmin
Name: test_project
Codifica caratteri: utf8mb4_bin
4. Creiamola tabella: product
– Id integer auto increment
– name char lenght=100
– price decimal scale=2 (10,2)
– description text
NB: phpMyAdmin a volte non imposta correttamente 10,2 convertendolo in automatico in 10,0, in questo caso selezionare il tab SQL e digitale
1 | ALTER TABLE `product` CHANGE `price` `price` DECIMAL(10,2) NOT NULL; |
5. src/AppBundle/Entity/Product.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | <?php // src/AppBundle/Entity/Product.php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="product") */ class Product { // ------------------------------------------------------------------------- // Proprietà --------------------------------------------------------------- // ------------------------------------------------------------------------- /** * @ORM\Column(type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id ; /** * @ORM\Column(type="string", length=100) */ private $name ; /** * @ORM\Column(type="decimal", scale=2) */ private $price ; /** * @ORM\Column(type="text") */ private $description ; // ------------------------------------------------------------------------- // Metodi ------------------------------------------------------------------ // ------------------------------------------------------------------------- public function getId() // ottieni { return $this ->id; // assegna il valore che proviene dall'istanza $this-> } public function setId( $id ) // setta { $this ->id = $id ; } // ------------------------------------------------------------------------- public function getName() // ottieni { return $this ->name; // assegna il valore che proviene dall'istanza $this-> } public function setName( $name ) // setta { $this ->name = $name ; } // ------------------------------------------------------------------------- public function getPrice() // ottieni { return $this ->price; // assegna il valore che proviene dall'istanza $this-> } public function setPrice( $price ) // setta { $this ->price = $price ; } // ------------------------------------------------------------------------- public function getDescription() // ottieni { return $this ->description; // assegna il valore che proviene dall'istanza $this-> } public function setDescription( $description ) // setta { $this ->description = $description ; } } // end class Product |
Notare che nel creare l’oggetto aggiungo le specifiche per il salvaggio nel DB con la notazione /**
1 2 3 4 5 6 | use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="product") */ |
6. src/AppBundle/Controller/SaveProduct.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | <?php // src/AppBundle/Controller/SaveProduct.php namespace AppBundle\Controller; use AppBundle\Entity\Product; // Product.php che ho creato io use Symfony\Bundle\FrameworkBundle\Controller\Controller; // il bundle controller Symfont use Symfony\Component\HttpFoundation\Response; // namespace di Symfony per response() use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; // namespace per utilizzare @Route class SaveProduct extends Controller { /** * @Route("/saveproduct") */ public function createAction() { // 1. Crea i prodotti // primo prodotto ---------------------------------------------------------- $product = new Product(); $product ->setName( 'Keyboard' ); $product ->setPrice(19.99); $product ->setDescription( 'Ergonomic and stylish!' ); // ------------------------------------------------------------------------- // secondo prodotto -------------------------------------------------------- $anotherProduct = new Product(); $anotherProduct ->setName( 'Mouse' ); $anotherProduct ->setPrice(5.99); $anotherProduct ->setDescription( 'Really cool!' ); // ------------------------------------------------------------------------- // debug code -------------------------------------------------------------- echo 'Primo Debug' ; var_dump( $product ); // debug notare che id = 'null', non è un problema // il campo Id lo gestisce Doctrine automaticamente, Id resta nel DB anche alla cancellazione del prodotto var_dump( $anotherProduct ); // die('Stop Here'); // debug // 2. accesso al DB -------------------------------------------------------- $em = $this ->getDoctrine()->getManager(); // carica il metodo di Doctrin per la gestione del DB // 3. INSERIMENTO PRIMO OGGETTO -------------------------------------------- // tells Doctrine you want to (eventually) save the Product (no queries yet) $em ->persist( $product ); // prepara l'oggetto in Cache per velocizzarsi ma NON salva ancora // actually executes the queries (i.e. the INSERT query) $em -> flush (); // metodo flush() esegue INSERT // 4. INSERIMENTO SECONDO OGGETTO ------------------------------------------ $em ->persist( $anotherProduct ); $em -> flush (); // 5. RIMOZIONE SECONDO OGGETTO -------------------------------------------- $em ->remove( $anotherProduct ); $em -> flush (); // mostra id prelevandolo dall'oggetto $product, non sta leggendo dal DB return new Response( 'Saved new product with id ' . $product ->getId() ); } // END createAction() } // END class Saveproduct |
Come funziona?
1. Istanzio per creare 2 prodotti $product = new Product(); – $anotherProduct = new Product();
2. $em = $this->getDoctrine()->getManager(); – richiamo il metodo di Doctrine per la gestione del DB
3a. $em->persist($product); – richiamo il metodo persist per creare una query temporanea in cache
3b. $em->flush(); – avvia la query INSERT
4a. $em->remove($anotherProduct); – richiamo il metodo remove per creare una query temporanea in cache
4b. $em->flush(); – avvia la query DELETE
Bibliografia:
symfony.com/doc/current/doctrine.html
docs.doctrine-project.org
docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/basic-mapping.html#quoting-reserved-words