Install
Doctrine is the best set of PHP libraries to work with databases.
composer create-project symfony/skeleton doctrine
cd doctrine/
composer require symfony/orm-pack
composer require --dev symfony/maker-bundle
symfony server:start
http://localhost:8000
Database
DATABASE_URL="mysql://admin:password@127.0.0.1:3306/db_name?serverVersion=8.0.27"
php bin/console doctrine:database:create
php bin/console make:entity
php bin/console make:migration
php bin/console doctrine:migrations:migrate
php bin/console make:entity
php bin/console make:migration
php bin/console doctrine:migrations:migrate
Controller
You can create a new Product object and save it in database.
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Product;
use Doctrine\Persistence\ManagerRegistry;
class ProductController extends AbstractController
{
public function index(ManagerRegistry $doctrine): Response
{
$entityManager = $doctrine->getManager();
$product = new Product();
$product->setName('Desk');
$product->setPrice(500);
$product->setDescription('Ergonomic');
$entityManager->persist($product);
$entityManager->flush();
return new Response('New product saved, id: ' . $product->getId());
}
public function fetch_one(ManagerRegistry $doctrine): Response
{
$repository = $doctrine->getRepository(Product::class);
$one = $repository->findOneBy(['id' => 2]);
return new Response(
'Product id 2, name: ' . $one->getName());
}
public function fetch_sql(ManagerRegistry $doctrine): Response
{
$repository = $doctrine->getRepository(Product::class);
$data = $repository->findAllGreaterThanId(3);
$last = $data[0];
return new Response(
'Last from list (id > 3): ' . $last['id']);
}
}
Fetch
You can query directly with SQL if you need to.
namespace App\Repository;
use App\Entity\Product;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class ProductRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Product::class);
}
public function findAllGreaterThanId(int $id): array
{
$conn = $this->getEntityManager()->getConnection();
$sql = "
SELECT * FROM product p
WHERE p.id > :id
ORDER BY p.id DESC
";
$stmt = $conn->prepare($sql);
$result = $stmt->executeQuery(['id' => $id]);
return $result->fetchAllAssociative();
}
}