please tell me how to get entity manager on laminas framework
Controller:
public function signupAction()
{
$user = new Users();
$user->setUsername('Test');
$user->setEmail('test#mail.ru');
$user->setNumber('+79168415532');
// this one i have persist() and flush()
}
To elaborate on #Aleksey Blossom's answer you need to create a factory from which to inject the entity manager.
use Laminas\ServiceManager\Factory\FactoryInterface;
use Interop\Container\ContainerInterface;
use Doctrine\ORM\EntityManager;
use YourModule\Controller\CategoryController;
class CategoryControllerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null)
{
$entityManger = $container->get(EntityManager::class);
return new CategoryController($entityManger);
}
}
and in your controller
use Laminas\Mvc\Controller\AbstractActionController;
use Doctrine\ORM\EntityManager;
class CategoryController extends AbstractActionController
{
private EntityManager $entityManager;
public function __construct(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}
public function signupAction()
{
$user = new Users();
$user->setUsername('Test');
$user->setEmail('test#mail.ru');
$user->setNumber('+79168415532');
$this->entityManager->persist($user);
$this->entityManager->flush();
}
}
As a side note I would also consider placing your business logic into models.
Create Factory
class CategoryControllerFactory implements FactoryInterface
{
public function __invoke(\Interop\Container\ContainerInterface $container, $requestedName, ?array $options = null)
{
$entityManger = $container->get(\Doctrine\ORM\EntityManager::class);
return new CategoryController($entityManger);
}
}
Related
I have tried to create DataFixtures, I think that my code is correct because if I tried on another project it's worked. So I don't understand why just in that my actual project , the Object Manager isn't working and my IDE is underlying Object Manager.
My error:
Declaration must be compatible with FixtureInterface->load(manager: \Doctrine\Persistence\ObjectManager)
My code:
<?php
namespace App\DataFixtures;
use App\Entity\User;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class UserFixtures extends Fixture
{
public function __construct(UserPasswordEncoderInterface $passwordEncoder)
{
$this->passwordEncoder =$passwordEncoder;
}
public function load(ObjectManager $manager)
{
foreach ($this->getUserData() as [$email,$password,$lastname,$firstname,$company,$language,$enabled,$pictures])
{
$user = new User();
$user->setEmail($email);
$user->setPassword($this->passwordEncoder->encodePassword($user,$password));
$user->setLastname($lastname);
$user->setFirstname($firstname);
$user->setCompany($company);
$user->setLanguage($language);
$user->setEnabled($enabled);
$user->setPictures($pictures);
}
$manager->flush();
}
private function getUserData() : array {
return [
['test#gmail.com','test','paul','marc','WKCompany','BE',1,'https://media.istockphoto.com/photos/businessman-silhouette-as-avatar-or-default-profile-picture-picture-id476085198?k=6&m=476085198&s=612x612&w=0&h=5cDQxXHFzgyz8qYeBQu2gCZq1_TN0z40e_8ayzne0X0=']
];
}
}
it looks simple type error. I only changed ObjectManager namespace.
use App\Entity\User;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class UserFixtures extends Fixture
{
public function __construct(UserPasswordEncoderInterface $passwordEncoder)
{
$this->passwordEncoder =$passwordEncoder;
}
public function load(ObjectManager $manager)
{
foreach ($this->getUserData() as [$email,$password,$lastname,$firstname,$company,$language,$enabled,$pictures])
{
$user = new User();
$user->setEmail($email);
$user->setPassword($this->passwordEncoder->encodePassword($user,$password));
$user->setLastname($lastname);
$user->setFirstname($firstname);
$user->setCompany($company);
$user->setLanguage($language);
$user->setEnabled($enabled);
$user->setPictures($pictures);
}
$manager->flush();
}
private function getUserData() : array {
return [
['test#gmail.com','test','paul','marc','WKCompany','BE',1,'https://media.istockphoto.com/photos/businessman-silhouette-as-avatar-or-default-profile-picture-picture-id476085198?k=6&m=476085198&s=612x612&w=0&h=5cDQxXHFzgyz8qYeBQu2gCZq1_TN0z40e_8ayzne0X0=']
];
}
}
I am trying to inject my BaseService within antoher service where I need to call my repository that I wrote in BaseService.
I think it's pretty simple thing but it marks __construct part with :
Missing parent constructor call
I made that logic in BaseService and it works
class BaseService
{
/** #var ContainerInterface */
public $container;
public $em;
public function __construct(ContainerInterface $container, EntityManagerInterface $em)
{
$this->container = $container;
$this->em = $em;
}
/**
* #return \Doctrine\Common\Persistence\ObjectRepository|\Doctrine\ORM\EntityRepository
*/
public function getMyDataRepository()
{
return $this->em->getRepository(MyData::class);
}
}
and my other service:
class DataService extends AbstractAdmin
{
public function __construct(BaseService $baseService)
{
$this->baseService = $baseService;
}
public function getTransactions(Card $card)
{
return $this->getMyDataRepository()
->createQueryBuilder('c')
->getQuery();
}
}
I found an answer.
I did it like this:
public $baseService;
public function __construct($code, $class, $baseControllerName, BaseService $baseService)
{
parent::__construct($code, $class, $baseControllerName);
$this->baseService = $baseService;
}
As Abstract Admin has its constructor.
You forgot to add parent constructor of AbstractAdmin on DataService.
class DataService extends AbstractAdmin
{
public function __construct(BaseService $baseService)
{
parent::__construct(AbstractAdmin dependencies goes here);
$this->baseService = $baseService;
}
public function getTransactions(Card $card)
{
return $this->getMyDataRepository()
->createQueryBuilder('c')
->getQuery();
}
I dont know which dependencies need your AbstractAdmin
trying to make an subscriber for Entity actions (CRUD) and cannot figure it out.
I know there is a way, where I can make listener and send him 3 different events, but that's not what I want to reach, I dont even think is good solution.
Event Subscriber
<?php
namespace App\EventListener;
use App\Entity\Log;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
/**
* Part of program created by David Jungman
* #author David Jungman <davidjungman.web#gmail.com>
*/
class EntitySubscriber implements EventSubscriberInterface
{
/**
* #var EntityManagerInterface
*/
private $em;
/**
* #var TokenStorageInterface
*/
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage, EntityManagerInterface $em)
{
$this->em = $em;
$this->tokenStorage = $tokenStorage;
}
public static function getSubscribedEvents()
{
return array(
Events::postPersist,
Events::postUpdate,
Events::postRemove,
);
}
public function postUpdate(LifecycleEventArgs $args)
{
$this->logEvent($args, "remove");
}
public function postRemove(LifecycleEventArgs $args)
{
$this->logEvent($args, "remove");
}
public function postPersist(LifecycleEventArgs $args)
{
$this->logEvent($args, "create");
}
private function logEvent(LifecycleEventArgs $args, string $method)
{
$entity = $args->getEntity();
if($entity->getShortName() != "Log")
{
$user = $this->tokenStorage->getToken()->getUser();
$log = new Log();
$log
->setUser($user)
->setAffectedTable($entity->getShortName())
->setAffectedItem($entity->getId())
->setAction($method)
->setCreatedAt();
$this->em->persist($log);
$this->em->flush();
}
}
}
and my Service.yaml part
App\EventListener\EntitySubscriber:
tags:
- { name: doctrine.event_subscriber, connection: default }
I have tried:
I've looked into these 2 official tutorials:
-https://symfony.com/doc/current/event_dispatcher.html
-https://symfony.com/doc/current/doctrine/event_listeners_subscribers.html
but neither helped.. when I use shown part of config, my computer freeze.
When I try to debug it, I can see these methods active
( php bin/console debug:event-dispatcher )
but they are listening on "event" event
Doctrine has it's own events handler/subscriber system. However, with the class Symfony\Component\EventDispatcher\EventSubscriberInterface; that you are implementing, that is from the Symfony event system.
<?php
use Doctrine\ORM\Events;
use Doctrine\Common\EventSubscriber; // **the Doctrine Event subscriber interface**
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
class MyEventSubscriber implements EventSubscriber
{
public function getSubscribedEvents()
{
return array(
Events::postUpdate,
);
}
public function postUpdate(LifecycleEventArgs $args)
{
$entity = $args->getObject();
$entityManager = $args->getObjectManager();
// perhaps you only want to act on some "Product" entity
if ($entity instanceof Product) {
// do something with the Product
}
}
}
I am trying to unit test a form which has 2 dependencies (ObjectManager and EventDispatcher)
I had tried to follow official doc but without success.
My testing file:
<?php
namespace Lch\MediaBundle\Tests\Form;
use Lch\MediaBundle\Form\AddImageType;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;
class AddImageTypeTest extends TypeTestCase
{
private $entityManager;
private $eventDispatcher;
protected function setUp()
{
$this->entityManager = $this->createMock(ObjectManager::class);
$this->eventDispatcher = $this->createMock(EventDispatcher::class);
parent::setUp();
}
protected function getExtensions()
{
$type = new AddImageType($this->entityManager, $this->eventDispatcher);
return array(
new PreloadedExtension(array($type), array()),
);
}
public function testSubmitValidData()
{
$form = $this->factory->create(AddImageType::class);
}
}
I got this error when I execute my test suite:
TypeError: Argument 1 passed to
LCH\MediaBundle\Form\AddImageType::__construct() must implement
interface Doctrine\Common\Persistence\ObjectManager, none given,
called in
/home/matthieu/www/lch/media/src/Lch/MediaBundle/vendor/symfony/symfony/src/Symfony/Component/Form/FormRegistry.php
on line 85
It seems that the job I do in the getExtensions method is not working, but cannot figure it out.
Does anyone have a clue?
ObjectManager is an interface, meaning you can't instantiate or pass it directly to other constructors.
If you are using Doctrine, replace it with Doctrine\ORM\EntityManager which implements ObjectManager interface and can be instantiated, otherwise replace it with your own implementation.
<?php
namespace Lch\MediaBundle\Tests\Form;
use Lch\MediaBundle\Form\AddImageType;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;
class AddImageTypeTest extends TypeTestCase
{
private $entityManager;
private $eventDispatcher;
protected function setUp()
{
$this->entityManager = $this->createMock(EntityManager::class);
$this->eventDispatcher = $this->createMock(EventDispatcher::class);
parent::setUp();
}
protected function getExtensions()
{
$type = new AddImageType($this->entityManager, $this->eventDispatcher);
return array(
new PreloadedExtension(array($type), array()),
);
}
public function testSubmitValidData()
{
$form = $this->factory->create(AddImageType::class);
}
}
I'm trying to pre-populate a database with some User objects, but when I call $user->setPassword('some-password'); and then save the user object, the string 'some-password' is stored directly in the database, instead of the hashed+salted password.
My DataFixture class:
// Acme/SecurityBundle/DataFixtures/ORM/LoadUserData.php
<?php
namespace Acme\SecurityBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Acme\SecurityBundle\Entity\User;
class LoadUserData implements FixtureInterface
{
public function load(ObjectManager $manager)
{
$userAdmin = new User();
$userAdmin->setUsername('System');
$userAdmin->setEmail('system#example.com');
$userAdmin->setPassword('test');
$manager->persist($userAdmin);
$manager->flush();
}
}
And the relevant database output:
id username email salt password
1 System system#example.com 3f92m2tqa2kg8cookg84s4sow80880g test
Since you are using FOSUserBundle, you can use UserManager to do this. I would use this code (assuming you have $this->container set):
public function load(ObjectManager $manager)
{
$userManager = $this->container->get('fos_user.user_manager');
$userAdmin = $userManager->createUser();
$userAdmin->setUsername('System');
$userAdmin->setEmail('system#example.com');
$userAdmin->setPlainPassword('test');
$userAdmin->setEnabled(true);
$userManager->updateUser($userAdmin, true);
}
Call setPlainPassword instead.
<?php
namespace Acme\SecurityBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Acme\SecurityBundle\Entity\User;
class LoadUserData implements FixtureInterface, ContainerAwareInterface
{
private $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function load(ObjectManager $manager)
{
$userAdmin = new User();
$userAdmin->setUsername('System');
$userAdmin->setEmail('system#example.com');
$userAdmin->setPlainPassword('test');
$userAdmin->setRoles(array('ROLE_SUPER_ADMIN'));
$manager->persist($userAdmin);
$manager->flush();
}
}
Four lines of code and you are done. It will handle everything for you:
$userManager = $this->container->get('fos_user.user_manager');
$user->setPlainPassword($password);
$userManager->updatePassword($user);
This worked for me
public function load(ObjectManager $manager){
$userAdmin = new User();
$userAdmin->setUsername('admin');
$userAdmin->setPlainPassword('admin');
$userAdmin->setEmail('admin#gmail.com');
$userAdmin->setEnabled(true);
$manager->persist($userAdmin);
$manager->flush();
}
Note the difference when setting the password. Querying the database you find
id username username_canonical email email_canonical enabled salt password
2 admin admin admin#gmail.com admin#gmail.com 1 4gm0bx6jzocgksw0wws8kck04kg40o8 m2ZyJM2+oBIzt/NZdnOX4nFvjV/SWTU1qJqe6dWZ0UwLF5gB8N...
$userAdmin->setUsername('System');
$userAdmin->setEmail('system#example.com');
$userAdmin->setPlainPassword('test');
$userAdmin->setEnabled(true);
setPlainPassword works for me.
/**
* 添加用户
* #param $param
* #return int
*/
public function doAdd($param)
{
$entity = new User();
$em = $this->getEntityManager();
$entity->setUsername($param['username'])
->setPlainPassword($param['password'])
->setEmail($param['email'])
->setEnabled(true)
->setRealName($param['realName']);
$em->persist($entity);
$em->flush();
return $entity->getId();
}
Above worked for me, so I got some conclusion:
1. must use the setPlainPassword
2. must setEnabled(true)
Here a sample class to create an admin user via ORM Fixtures:
<?php
namespace Acme\SecurityBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Acme\SecurityBundle\Entity\User;
class LoadFOSAdminUser extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{
private $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function load(ObjectManager $manager)
{
$userManager = $this->container->get('fos_user.user_manager');
$userAdmin = $userManager->createUser();
$userAdmin->setUsername('admin');
$userAdmin->setEmail('admin#example.com');
$userAdmin->setPlainPassword('admin');
$userAdmin->setEnabled(true);
$userAdmin->setRoles(array('ROLE_ADMIN'));
$userManager->updateUser($userAdmin, true);
}
public function getOrder()
{
return 1;
}
}