Zend CRUD

I’ll now give you a complete CRUD (Create, Read, Update, Delete) implementation using Doctrine ORM in Zend Framework, along with additional queries and clear explanations at each step.


Use Case: User Entity

Let’s assume we have a User entity with the following fields:

  • id: integer (primary key)
  • name: string

Step 1: Inject EntityManager in Controller

Inject EntityManager link


Step 2: Create User Entity (module/Application/src/Entity/User.php)

namespace Application\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 */
class User
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

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

    // Getters and setters...
    public function getId(): ?int { return $this->id; }
    public function getName(): ?string { return $this->name; }
    public function setName(string $name): self { $this->name = $name; return $this; }
}


Step 4: CRUD Methods in Controller

Create User

public function createAction()
{
  $user = new User();
  $user->setName('John');
  $user->setEmail('john@example.com');
  $user->setIsActive(true);

  $this->entityManager->persist($user);
  $this->entityManager->flush();

  return new JsonModel(['message' => 'User created']);
}


Read All Users

public function indexAction()
{
  $users = $this->entityManager->getRepository(User::class)->findAll();
  return new JsonModel(['users' => $users]);
}


Update User

public function updateAction()
{
  $user = $this->entityManager->find(User::class, 1);
  if ($user) {
    $user->setName('Jane');
    $this->entityManager->flush();
  }

  return new JsonModel(['message' => 'User updated']);
}


Delete User

public function deleteAction()
{
  $user = $this->entityManager->find(User::class, 1);
  if ($user) {
    $this->entityManager->remove($user);
    $this->entityManager->flush();
  }

  return new JsonModel(['message' => 'User deleted']);
}



Additional Queries

Find By Email

$user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => 'john@example.com']);


Filter Active Users

$users = $this->entityManager->getRepository(User::class)->findBy(['is_active' => true]);


Custom Query (DQL)

$query = $this->entityManager->createQuery('SELECT u FROM Application\Entity\User u WHERE u.is_active = 1');
$activeUsers = $query->getResult();

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.