Zend framework 3 - Doctrine entity not found - doctrine-orm

The purpose is to create a module in which to insert all the entities and then use them in the other modules. This is why I created a module called Entity in which I entered the entities. Unfortunately when I try to use one of these entities within the basic controller I get an error: class not found
This is my composer
"autoload": {
"psr-4": {
"Application\\": "module/Application/src/",
"Entity\\": "module/Entity/src/"
}
},
I already execute this command
composer dump-autoload
My entity class is under
module/Entity/src/Model/
This is my class
<?php
namespace Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* SysUserRole
*
* #ORM\Table(name="sys_user_role")
* #ORM\Entity
*/
class SysUserRole
{
/**
* #var int
*
* #ORM\Column(name="ID_SYS_USER_ROLE", type="integer", nullable=false, options={"unsigned"=true})
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idSysUserRole;
/**
* #var string
*
* #ORM\Column(name="NAME", type="string", length=100, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="DESCRIPTION", type="string", length=255, nullable=false)
*/
private $description;
/**
* #return int
*/
public function getIdSysUserRole()
{
return $this->idSysUserRole;
}
/**
* #param int $idSysUserRole
*/
public function setIdSysUserRole($idSysUserRole)
{
$this->idSysUserRole = $idSysUserRole;
}
/**
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* #param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}
}
This is my config\autoload\doctrine.global.php
'doctrine' => [
'connection' => [
'orm_default' => [
'driverClass' => PDOMySqlDriver::class,
'params' => [
'host' => 'localhost',
'user' => '***',
'password' => '****',
'dbname' => 'mydb',
'charset' => 'utf8',
'driverOptions' => array(
1002 => 'SET NAMES utf8'
)
]
],
],
'authentication' => [
'orm_default' => [
'object_manager' => 'Doctrine\ORM\EntityManager',
'identity_class' => 'Application\Entity\User',
'identity_property' => 'email',
'credential_property' => 'password',
],
],
'driver' => [
'entity_driver' => [
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => [__DIR__ . '/../../module/Entity/src/Model/']
],
'orm_default' => [
'drivers' => [
'\Entity' => 'entity_driver'
]
]
],
],
In controller action i try this
$entity = new SysUserRole();
The error is
Class 'Entity\SysUserRole' not found
edit:
the error is changed
I move this code inside a module.config.php
'doctrine' => [
'driver' => [
__NAMESPACE__ . '_driver' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => array(__DIR__ . '/../src/Model')
),
'orm_default' => [
'drivers' => [
//was \Entity
'Entity\Model' => __NAMESPACE__ . '_driver'
]
]
],
]
new error is
The class 'Entity\Model\SysUserRole' was not found in the chain configured namespaces \Entity\

Folder structure and psr-4 registered namespace. I would expect the Entity namespace to be Entity\Model with then the class name.
Btw, using a module for a purpose would probably be a better approach. Having Entities per module, for the purpose of the module (e.g. User and Profile Entity objects in the User module), makes sense.
namespace SomeSpace
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
return [
'doctrine' => [
'driver' => [
__NAMESPACE__ . '_driver' => [
'class' => AnnotationDriver::class,
'cache' => 'array',
'paths' => [
__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'src'
. DIRECTORY_SEPARATOR . 'Entity',
]
],
'orm_default' => [
'drivers' => [
__NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
],
],
],
],
];
The above config would be required per module, due to the usage of the __NAMESPACE__ and __DIR__ global constants.
NOTE: Make sure that namespace names match folder names, e.g.:
module\Address\Entity\Address (last is class name for Address.php)
Folder structure here is:
module\Address\Entity\**.php
Example: Entity class & associated composer.json
From example links:
composer.json
"autoload": {
"psr-4": {
"Keet\\Form\\Examples\\": "src/"
},
Address.php
<?php
namespace Keet\Form\Examples\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table(name="addresses")
* #ORM\Entity
*/
class Address extends AbstractEntity
{
...
}

Related

Inserting data to database using zf3 and doctrine

i'm trying to insert data to database but submitted forms does nothing.
this is my service manager:
class AutosManager
{
/**
* Entity manager.
* #var Doctrine\ORM\EntityManager;
*/
private $entityManager;
/**
* Constructor.
*/
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
}
public function addNewAutos($data)
{
$autos = new Autos();
$autos->setTitle($data['title']);
$autos->setDescription($data['description']);
$currentDate = date('Y-m-d H:i:s');
$autos->setDateCreated($currentDate);
$this->entityManager->persist($autos);
$this->entityManager->flush();
}
this is my controller addAction
public function addAction()
{
// Create the form.
$form = new PostForm();
if ($this->getRequest()->isPost()) {
// Get POST data.
$data = $this->params()->fromPost();
// Fill form with data.
$form->setData($data);
if ($form->isValid()) {
// Get validated form data.
$data = $form->getData();
$this->AutosManager->addNewAutos($data);
return $this->redirect()->toRoute('retrieve');
}
}
return new ViewModel([
'form' => $form
]);
}
i can retrieve data from database to the index page but i cannot add. hope to find the solution.
this is my Autos Entity
namespace Retrieve\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass="\Retrieve\Repository\AutosRepository")
* #ORM\Table(name="auto")
*/
class Autos
{
/**
* #ORM\Id
* #ORM\Column(name="id")
* #ORM\GeneratedValue
*/
protected $id;
/**
* #ORM\Column(name="title")
*/
protected $title;
/**
* #ORM\Column(name="description")
*/
protected $description;
/**
* #ORM\Column(name="featured")
*/
protected $featured;
/**
* #ORM\Column(name="date_created")
*/
protected $dateCreated;
/**
* Returns ID of this post.
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Sets ID of this post.
* #param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* Returns title.
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Sets title.
* #param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* Returns featured.
* #return integer
*/
public function getFeatured()
{
return $this->featured;
}
/**
* Sets featured.
* #param integer $featured
*/
public function setFeatured($featured)
{
$this->featured = $featured;
}
/**
* Returns post description.
*/
public function getDescription()
{
return $this->description;
}
/**
* Sets post description.
* #param type $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Returns the date when this post was created.
* #return string
*/
public function getDateCreated()
{
return $this->dateCreated;
}
/**
* Sets the date when this post was created.
* #param string $dateCreated
*/
public function setDateCreated($dateCreated)
{
$this->dateCreated = $dateCreated;
}
}
hope this helps to find solution.
I found the problem: it was an inputfilter element I wasn't using that was authenticating in forms. But the solution only brings me to a different problem:
Notice: Undefined index: title in C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php on line 38
Notice: Undefined index: description in C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php on line 39
Notice: Undefined index: featured in C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php on line 58
Message:
An exception occurred while executing 'INSERT INTO auto (title, description, featured, date_created) VALUES (?, ?, ?, ?)' with params [null, null, null, "2017-06-15 05:04:44"]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null
this is my form and fieldset
use Zend\Form\Fieldset;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use BusinessGhana\Entity\Autos;
class AddFieldset extends Fieldset
{
protected $objectManager;
public function init()
{
$this->add([
'type' => 'text',
'name' => 'title',
'attributes' => [
'id' => 'autoTitle'
],
'options' => [
'label' => 'Title',
'display_empty_item' => true,
'empty_item_label' => 'Maximum of 60 characters',
],
]);
$this->add([
'type' => 'textarea',
'name' => 'description',
'attributes' => [
'id' => 'autoDescription'
],
'options' => [
'label' => 'Description',
'display_empty_item' => true,
'empty_item_label' => 'description',
],
]);
$this->add([
'type' => 'radio',
'name' => 'featured',
'attributes' => [
'id' => 'autoFeatured'
],
'options' => array(
'label' => 'Featured',
'value_options' => array(
array('value' => '0',
'label' => 'No',
'selected' => true,
'label_attributes' => array(
'class' => 'col-sm-2 btn btn-default',
),
),
array(
'value' => '1',
'label' => 'Yes',
'label_attributes' => array(
'class' => 'col-sm-2 btn btn-danger',
),
),
),
'column-size' => 'sm-12',
'label_attributes' => array(
'class' => 'col-sm-2',
),
),
]);
}
}
use Zend\Form\Form;
//use Zend\InputFilter\InputFilter;
class AddForm extends Form
{
public function init()
{
$this->add([
'name' => 'dependentForm',
'type' => AddFieldset::class,
]);
$this->add([
'type' => 'submit',
'name' => 'submit',
'attributes' => [
'value' => 'Submit',
],
]);
}
}
i know hydration can solve this problem but i dont know how to use it yet.

Entity Mapping doesn't work

I'm trying to use Doctrine2 with ZF3. All components have been installed with composer.
When I try to use an Entity I have an exception :
Doctrine\Common\Persistence\Mapping\MappingException
Class 'Application\Entity\Concours' does not exist
The exception is thrown when I use in the Controller's action :
$concours = $this->entityManager->getRepository(Concours::class);
I have the same problem if i use :
$entity = new Concours();
or
$entity = new \Application\Entity\Concours();
I really don't understand why...
Thanks for help...
My configuration :
config/local.php
use Doctrine\DBAL\Driver\PDOMySql\Driver as PDOMySqlDriver;
return [
'doctrine' => [
'connection' => [
'orm_default' => [
'driverClass' => PDOMySqlDriver::class,
'params' => [
'host' => '127.0.0.1',
'user' => 'xxxx',
'password' => 'xxxx',
'dbname' => 'goch',
],
],
],
],
];
config/modules.config.php
return [
'Zend\Cache',
'Zend\Form',
'Zend\InputFilter',
'Zend\Filter',
'Zend\Paginator',
'Zend\Hydrator',
'Zend\Router',
'Zend\Validator',
'DoctrineModule',
'DoctrineORMModule',
'Application',
];
For Application Module,
module/Application/config/module.config.php
namespace Application;
use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
return [
'router' => [
'routes' => [
'home' => [
'type' => Literal::class,
'options' => [
'route' => '/',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
'application' => [
'type' => Segment::class,
'options' => [
'route' => '/application[/:action]',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
],
],
'controllers' => [
'factories' => [
Controller\IndexController::class => Controller\Factory\IndexControllerFactory::class,
],
],
'view_manager' => [
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => [
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
],
'template_path_stack' => [
__DIR__ . '/../view',
],
],
'doctrine' => [
'driver' => [
__NAMESPACE__ . '_driver' => [
'class' => AnnotationDriver::class,
'cache' => 'array',
'paths' => [__DIR__ . '/../src/Entity']
],
'orm_default' => [
'drivers' => [
__NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
]
]
]
]
];
My Controller (module/Application/src/Controller/IndexController.php) is :
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Doctrine\ORM\EntityManager;
use Application\Entity\Concours;
class IndexController extends AbstractActionController {
/**
* Entity manager.
* #var Doctrine\ORM\EntityManager
*/
private $entityManager;
// Constructor method is used to inject dependencies to the controller.
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
}
public function indexAction() {
return new ViewModel();
}
public function concoursAction(){
$concours=array();
$concours = $this->entityManager->getRepository(Concours::class);
// Render the view template
return new ViewModel([
'concours' => $concours
]);
}
}
And the associated Factory
namespace Application\Controller\Factory;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
use Application\Controller\IndexController;
/**
* This is the factory for IndexController. Its purpose is to instantiate the
* controller.
*/
class IndexControllerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container,
$requestedName, array $options = null)
{
$entityManager = $container->get('doctrine.entitymanager.orm_default');
// Instantiate the controller and inject dependencies
return new IndexController($entityManager);
}
}
All my Entities class files are in module/Application/src/Application/Entity/,
here is the Concours Entity Class:
<?php
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Concours
*
* #ORM\Table(name="Concours", uniqueConstraints={#ORM\UniqueConstraint(name="numero_UNIQUE", columns={"numero"})})
* #ORM\Entity
*/
class Concours
{
/**
* #var integer
*
* #ORM\Column(name="ref", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $ref;
...
}
Here is your problem:
All my Entities class files are in
module/Application/src/Application/Entity/
Zend 3 uses PSR-4 instead of PSR-0 which is considered as depracated. You can confirm it by checking composer.json file. You should see following declaration:
"autoload": {
"psr-4": {
"Application\\": "module/Application/src/",
}
},
In PSR-0 if you define Foo\Bar namespace is achored in src/ it will look for class in src/Foo/Bar/{your_class}.php while in PSR-4 it will look in src/{your_class}.php.
So... to fix your problem. Move Concours entity from:
module/Application/src/Application/Entity/
to:
module/Application/src/Entity/

Symfony 2 knplabs form translation - best way to change the referenceColumName

A2lix required 'id' as referenceColumName. But I've entities with a different columName (e.g. ProductID instead of id). So I get error when I try to update my DB via doctrine:schema:update --force.
Example of my entity
class Period
{
use ORMBehaviors\Translatable\Translatable,
ORMBehaviors\Timestampable\Timestampable,
ORMBehaviors\SoftDeletable\SoftDeletable
;
/**
* #var integer
*
* #ORM\Column(name="PeriodID", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
...
Part of the TranslatableSubscriber class of KnpDoctrineBehaviors Package
...
private function mapTranslatable(ClassMetadata $classMetadata)
{
if (!$classMetadata->hasAssociation('translations')) {
$classMetadata->mapOneToMany([
'fieldName' => 'translations',
'mappedBy' => 'translatable',
'indexBy' => 'locale',
'cascade' => ['persist', 'merge', 'remove'],
'fetch' => $this->translatableFetchMode,
'targetEntity' => $classMetadata->getReflectionClass()->getMethod('getTranslationEntityClass')->invoke(null),
'orphanRemoval' => true
]);
}
}
private function mapTranslation(ClassMetadata $classMetadata)
{
if (!$classMetadata->hasAssociation('translatable')) {
$classMetadata->mapManyToOne([
'fieldName' => 'translatable',
'inversedBy' => 'translations',
'fetch' => $this->translationFetchMode,
'joinColumns' => [[
'name' => 'translatable_id',
'referencedColumnName' => 'id',
'onDelete' => 'CASCADE'
]],
'targetEntity' => $classMetadata->getReflectionClass()->getMethod('getTranslatableEntityClass')->invoke(null),
]);
}
$name = $classMetadata->getTableName().'_unique_translation';
if (!$this->hasUniqueTranslationConstraint($classMetadata, $name)) {
$classMetadata->table['uniqueConstraints'][$name] = [
'columns' => ['translatable_id', 'locale' ]
];
}
if (!$classMetadata->hasField('locale')) {
$classMetadata->mapField(array(
'fieldName' => 'locale',
'type' => 'string'
));
}
}
...
Any idea or help would be appreciate.
Many thanks ;-)
You can use:
association override
I tried to override properties but they are created by the subscriber and I got exceptions. You can also re-declare the annotation manyToOne on your entity class.
It works for me.

ZF2 - Multiple entities in a single form

I am working on a shopping checkout page which requires:
OrderPerson
PersonAddress (delivery)
Order (notes, time etc. not all items are on the form at present to keep it simple)
I have more or less worked out how to put this together however it requires some tidying up.
My form looks as follows:
To make the forms play nicely together I have setup a CheckoutForm that includes the OrderPerson, PersonAddress and Order Fieldsets:
<?php
namespace MyCart\Form;
use Zend\Form\Element;
use Zend\Form\Fieldset;
use Zend\Form\Form;
use Zend\InputFilter\InputFilterInterface;
class CheckoutForm extends Form
{
public function __construct(
InputFilterInterface $orderFilter,
InputFilterInterface $orderPersonFilter,
InputFilterInterface $personAddressFilter,
$name = null,
$options = array()
) {
parent::__construct('checkout', $options);
$this->orderFilter = $orderFilter;
$this->orderPersonFilter = $orderPersonFilter;
$this->personAddressFilter = $personAddressFilter;
}
public function init()
{
$this->add(
[
'name' => 'csrfcheck',
'type' => 'csrf'
]
);
$this->add(
[
'name' => 'order',
'type' => OrderFieldset::class,
'options' => [
'use_as_base_fieldset' => true
]
]
);
$this->add(
[
'name' => 'order-person',
'type' => OrderPersonFieldset::class,
'options' => [
'use_as_base_fieldset' => true
]
]
);
$this->add(
[
'name' => 'person-address',
'type' => PersonAddressFieldset::class,
'options' => [
'use_as_base_fieldset' => true
]
]
);
$this->add(
[
'name' => 'submit',
'type' => 'submit',
'attributes' => [
'value' => 'Update',
'class' => 'form-element'
]
]
);
$this->getInputFilter()->add($this->orderFilter, 'order');
$this->getInputFilter()->add($this->orderPersonFilter, 'order-person');
$this->getInputFilter()->add($this->personAddressFilter, 'person-address');
}
}
The Checkout Form has a factory:
<?php
namespace MyCart\Form\Factory;
use MyCart\Form\CheckoutForm;
use MyCart\InputFilter\OrderFilter;
use MyCart\InputFilter\OrderPersonFilter;
use MyCart\InputFilter\PersonAddressFilter;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class CheckoutFormFactory implements FactoryInterface
{
/**
* Create service
*
* #param ServiceLocatorInterface $serviceLocator
* #return mixed
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$inputFilter = $serviceLocator->getServiceLocator()->get('InputFilterManager');
return new CheckoutForm(
$inputFilter->get(OrderFilter::class),
$inputFilter->get(OrderPersonFilter::class),
$inputFilter->get(PersonAddressFilter::class)
);
}
}
AS you can see the Checkout Form references the three input filters that are all constructed in the same manner. I have the OrderPerson fieldset here as a reference:
<?php
namespace MyCart\Form;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject;
use MyCart\Entity\OrderPerson;
use Zend\Form\Element;
use Zend\Form\Fieldset;
class OrderPersonFieldset extends Fieldset
{
/**
* #var \Doctrine\Common\Persistence\ObjectManager
* #access protected
*/
protected $objectManager;
/**
* #param ObjectManager $objectManager
* #param OrderPerson $orderPrototype
* #param null $name
* #param array $options
*/
public function __construct(
ObjectManager $objectManager,
OrderPerson $orderPrototype,
$name = null,
$options = array()
) {
parent::__construct($name, $options);
$this->objectManager = $objectManager;
$this->setHydrator(new DoctrineObject($objectManager));
$this->setObject($orderPrototype);
}
public function init()
{
$this->add(
[
'name' => 'id',
'type' => 'hidden',
]
);
$this->add(
[
'name' => 'rbu_user_id',
'type' => 'hidden',
]
);
$this->add(
[
'type' => 'text',
'name' => 'email',
'attributes' => [
'class' => 'form-control',
'required' => 'required',
],
'options' => [
'label' => 'Email Address',
'instructions' => 'Please enter your email address',
],
]
);
//etc...
}
}
On execution of the form the CheckoutController is called and this is where I am unsure of what to do or how to save the various objects, this is what I have so far:
public function indexAction()
{
//Pre check stuff here
//Start the form processing
$prg = $this->prg();
if ($prg instanceof Response) {
return $prg;
} elseif ($prg === false) {
//If logged in
if ( $this->authService->hasIdentity()) {
//Update the OrderPerson entity
$user_id = $this->identity()->getId();
$userObject = $this->userService->find($user_id);
$orderPersonEntity = new OrderPerson();
$orderPersonEntity->setRbuUser($userObject);
$orderPersonEntity->setFirstname($userObject->getFirstname());
$orderPersonEntity->setSurname($userObject->getSurname());
$this->checkoutForm->bind($orderPersonEntity);
//Update the person address entity
$personAddress = new PersonAddress();
$personAddress->setAddress1($userObject->getAddress1());
$personAddress->setAddress2($userObject->getAddress2());
$this->checkoutForm->bind($personAddress);
//Update the order entity
}
return new ViewModel(
array(
'cart' => $cart,
'form' => $this->checkoutForm
)
);
}
$this->checkoutForm->setData($prg);
if (!$this->checkoutForm->isValid()) {
return new ViewModel(
array(
'cart' => $cart,
'form' => $this->checkoutForm
)
);
}
$checkoutObject = $this->checkoutForm->getData();
die(var_dump($checkoutObject));
Dumping the result here outputs only the person address object:
object(MyCart\Entity\PersonAddress)[1177]
private 'id' => null
private 'address1' => string 'xx' (length=2)
private 'address2' => string 'xx' (length=2)
private 'region' => null
private 'postCode' => string 'xx' (length=2)
private 'city' => string 'xx' (length=2)
private 'country' => string 'xx' (length=2)
private 'created' => null
private 'modified' => null
private 'orderPerson' => null
So my question is simply, is this the right thinking and how do I complete this so that I can save the three entities in a single go?

Possible database configuration problems

I'm a new Zend developper and I have got some conception problem's (especially with doctrine).
I've got a Class which is called MyAuthenticationProcess.
This class is trying to authenticate an User by verifiying his identity on a Database.
As I saw over the internet, I should implement 3 things in order to communicate with my dataBase.
First of all, I have to add those lines in my module.config.php
'doctrine' => array(
'driver' => array(
__NAMESPACE__. '_driver' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity')
),
'orm_default' => array(
'drivers' => array(
__NAMESPACE__.'\Entity' => __NAMESPACE__.'_driver'
)
)
)
),
Secondly I have to create a file which will contains my Entity. I created this file in Authentification/Entity/User.php
Here is the code of this file :
<?php
namespace Authentification\Entity;
use Doctrine\ORM\Mapping as ORM;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
/**
* A User table.
*
* #ORM\Entity
* #ORM\Table(name="user")
* #property string $login
* #property string $password
* #property int $id
*/
class User {
/**
* #ORM\Id
* #ORM\Column(type="integer");
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string")
*/
protected $login;
/**
* #ORM\Column(type="string")
*/
protected $password;
/**
* Magic getter to expose protected properties.
*
* #param string $property
* #return mixed
*/
public function __get($property)
{
return $this->$property;
}
/**
* Magic setter to save protected properties.
*
* #param string $property
* #param mixed $value
*/
public function __set($property, $value)
{
$this->$property = $value;
}
}
?>
And to finish I added this configuration into this file : config/autoload/local.php
<?php
return array(
'doctrine' => array(
'connection' => array(
'orm_default' => array(
'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
'params' => array(
'host' => 'localhost',
'port' => '3306',
'user' => 'root',
'password' => '',
'dbname' => 'zf2tutorial',
)
)
)
),
);
The problem that I have now is for accessing to my dataBase.
I guess it's a problem of configuration.
In my class MyAuthenticationProcess I'm trying to get all the entries of my table "User". But I can't.
Here is the code that I used to do so :
$users = $this->getEntityManager()->getRepository('Authentification\Entity\User')->findAll() ;
var_dump($users) ;
And here is the error that I get :
<br />
<b>Fatal error</b>: Uncaught exception 'Zend\View\Exception\RuntimeException' with message 'Zend\View\Renderer\PhpRenderer::render: Unable to render template "layout/layout"; resolver could not resolve to a file' in xampp\htdocs\kjsencha\vendor\zendframework\zendframework\library\Zend\View\Renderer\PhpRenderer.php:457
Stack trace:
#0 xampp\htdocs\kjsencha\vendor\zendframework\zendframework\library\Zend\View\View.php(201): Zend\View\Renderer\PhpRenderer->render(Object(Zend\View\Model\ViewModel))
#1 xampp\htdocs\kjsencha\vendor\zendframework\zendframework\library\Zend\Mvc\View\Http\DefaultRenderingStrategy.php(126): Zend\View\View->render(Object(Zend\View\Model\ViewModel))
#2 [internal function]: Zend\Mvc\View\Http\DefaultRenderingStrategy->render(Object(Zend\Mvc\MvcEvent))
#3 xampp\htdocs\kjsencha\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(460): call_user_func(Array, Object(Zend\Mvc\MvcEvent)) in <b>\xampp\htdocs\kjsencha\vendor\zendframework\zendframework\library\Zend\View\Renderer\PhpRenderer.php</b> on line <b>457</b><br />
To make sure that is a problem of configuration I tried to know if the connection was established by using this :
$users = $this->getEntityManager()->getConnection() ;
var_dump($users) ;
I was surprise to see that users equals to NULL.
Do you have any idea where the problem came from ?
Thank you for your help.
I finally found where my problem came from =D
It was my table structure in my database. It was not similar to my entity files, so I change it and now it work.
Hope my post will help someone else which has the same problem.