8000 [DependencyInjection][Doctrine][Form] Add type declarations to Form, DI and Doctrine articles by wouterj · Pull Request #14525 · symfony/symfony-docs · GitHub
[go: up one dir, main page]

Skip to content

[DependencyInjection][Doctrine][Form] Add type declarations to Form, DI and Doctrine articles #14525

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 21, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Added PHP types to the Doctrine related articles
  • Loading branch information
wouterj committed Nov 21, 2020
commit 90c83b214c39c26633c3f7a0d4b8541bef6c6a26
193 changes: 116 additions & 77 deletions doctrine.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ The database connection information is stored as an environment variable called

# to use sqlite:
# DATABASE_URL="sqlite:///%kernel.project_dir%/var/app.db"

# to use postgresql:
# DATABASE_URL="postgresql://db_user:db_password@127.0.0.1:5432/db_name?serverVersion=11&charset=utf8"

Expand Down Expand Up @@ -506,46 +506,60 @@ Fetching an object back out of the database is even easier. Suppose you want to
be able to go to ``/product/1`` to see your new product::

// src/Controller/ProductController.php
namespace App\Controller;

use App\Entity\Product;
use Symfony\Component\HttpFoundation\Response;
// ...

/**
* @Route("/product/{id}", name="product_show")
*/
public function show($id)
class ProductController extends AbstractController
{
$product = $this->getDoctrine()
->getRepository(Product::class)
->find($id);

if (!$product) {
throw $this->createNotFoundException(
'No product found for id '.$id
);
}
/**
* @Route("/product/{id}", name="product_show")
*/
public function show(int $id): Response
{
$product = $this->getDoctrine()
->getRepository(Product::class)
->find($id);

if (!$product) {
throw $this->createNotFoundException(
'No product found for id '.$id
);
}

return new Response('Check out this great product: '.$product->getName());
return new Response('Check out this great product: '.$product->getName());

// or render a template
// in the template, print things with {{ product.name }}
// return $this->render('product/show.html.twig', ['product' => $product]);
// or render a template
// in the template, print things with {{ product.name }}
// return $this->render('product/show.html.twig', ['product' => $product]);
}
< 8000 /td> }

Another possibility is to use the ``ProductRepository`` using Symfony's autowiring
and injected by the dependency injection container::

// src/Controller/ProductController.php
// ...
namespace App\Controller;

use App\Entity\Product;
use App\Repository\ProductRepository;
use Symfony\Component\HttpFoundation\Response;
// ...

/**
* @Route("/product/{id}", name="product_show")
*/
public function show($id, ProductRepository $productRepository)
class ProductController extends AbstractController
{
$product = $productRepository
->find($id);
/**
* @Route("/product/{id}", name="product_show")
*/
public function show(int $id, ProductRepository $productRepository): Response
{
$product = $productRepository
->find($id);

// ...
// ...
}
}

Try it out!
Expand Down Expand Up @@ -611,15 +625,23 @@ for you automatically! First, install the bundle in case you don't have it:
Now, simplify your controller::

// src/Controller/ProductController.php
namespace App\Controller;

use App\Entity\Product;
use App\Repository\ProductRepository;
use Symfony\Component\HttpFoundation\Response;
// ...

/**
* @Route("/product/{id}", name="product_show")
*/
public function show(Product $ 8000 product)
class ProductController extends AbstractController
{
// use the Product!
// ...
/**
* @Route("/product/{id}", name="product_show")
*/
public function show(Product $product): Response
{
// use the Product!
// ...
}
}

That's it! The bundle uses the ``{id}`` from the route to query for the ``Product``
Expand All @@ -633,26 +655,37 @@ Updating an Object
Once you've fetched an object from Doctrine, you interact with it the same as
with any PHP model::

/**
* @Route("/product/edit/{id}")
*/
public function update($id)
// src/Controller/ProductController.php
namespace App\Controller;

use App\Entity\Product;
use App\Repository\ProductRepository;
use Symfony\Component\HttpFoundation\Response;
// ...

class ProductController extends AbstractController
{
$entityManager = $this->getDoctrine()->getManager();
$product = $entityManager->getRepository(Product::class)->find($id);
/**
* @Route("/product/edit/{id}")
*/
public function update(int $id): Response
{
$entityManager = $this->getDoctrine()->getManager();
$product = $entityManager->getRepository(Product::class)->find($id);

if (!$product) {
throw $this->createNotFoundException(
'No product found for id '.$id
);
}
if (!$product) {
throw $this->createNotFoundException(
'No product found for id '.$id
);
}
8000
$product->setName('New product name!');
$entityManager->flush();
$product->setName('New product name!');
$entityManager->flush();

return $this->redirectToRoute('product_show', [
'id' => $product->getId()
]);
return $this->redirectToRoute('product_show', [
'id' => $product->getId()
]);
}
}

Using Doctrine to edit an existing product consists of three steps:
Expand Down Expand Up @@ -728,7 +761,7 @@ a new method for this to your repository::
/**
* @return Product[]
*/
public function findAllGreaterThanPrice($price): array
public function findAllGreaterThanPrice(int $price): array
{
$entityManager = $this->getEntityManager();

Expand Down Expand Up @@ -773,25 +806,28 @@ based on PHP conditions)::
// src/Repository/ProductRepository.php

// ...
public function findAllGreaterThanPrice($price, $includeUnavailableProducts = false): array
class ProductRepository extends ServiceEntityRepository
{
// automatically knows to select Products
// the "p" is an alias you'll use in the rest of the query
$qb = $this->createQueryBuilder('p')
->where('p.price > :price')
->setParameter('price', $price)
->orderBy('p.price', 'ASC');

if (!$includeUnavailableProducts) {
$qb->andWhere('p.available = TRUE');
}
public function findAllGreaterThanPrice(int $price, bool $includeUnavailableProducts = false): array
{
// automatically knows to select Products
// the "p" is an alias you'll use in the rest of the query
$qb = $this->createQueryBuilder('p')
->where('p.price > :price')
->setParameter('price', $price)
->orderBy('p.price', 'ASC');

if (!$includeUnavailableProducts) {
$qb->andWhere('p.available = TRUE');
}

$query = $qb->getQuery();
$query = $qb->getQuery();

return $query->execute();
return $query->execute();

// to get just one result:
// $product = $query->setMaxResults(1)->getOneOrNullResult();
// to get just one result:
// $product = $query->setMaxResults(1)->getOneOrNullResult();
}
}

Querying with SQL
Expand All @@ -802,20 +838,23 @@ In addition, you can query directly with SQL if you need to::
// src/Repository/ProductRepository.php

// ...
public function findAllGreaterThanPrice($price): array
class ProductRepository extends ServiceEntityRepository
{
$conn = $this->getEntityManager()->getConnection();

$sql = '
SELECT * FROM product p
WHERE p.price > :price
ORDER BY p.price ASC
';
$stmt = $conn->prepare($sql);
$stmt->execute(['price' => $price]);

// returns an array of arrays (i.e. a raw data set)
return $stmt->fetchAllAssociative();
public function findAllGreaterThanPrice(int $price): array
{
$conn = $this->getEntityManager()->getConnection();

$sql = '
SELECT * FROM product p
WHERE p.price > :price
ORDER BY p.price ASC
';
$stmt = $conn->prepare($sql);
$stmt->execute(['price' => $price]);

// returns an array of arrays (i.e. a raw data set)
return $stmt->fetchAllAssociative();
}
}

With SQL, you will get back raw data, not objects (unless you use the `NativeQuery`_
Expand Down
Loading
0