i have to fetch an entity object, based on the given domain of my application. Based on that entity, other services handle their requests.
Is there a way to store a static object or something like that? Or should i inject it into the other services, but where should i store it that way?
Thanks for any help
-- EDIT --
Now i have the following Service factory to return the wantend entity. But now i have the problem, that in case of the default domain, no entity exists and my application crashes because I can't return a null value in the factory. How can I solve that?
namespace Client\Factory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class ClientFactory implements FactoryInterface {
/**
* #param \Zend\ServiceManager\ServiceLocatorInterface $serviceLocator
* #return \Client\Entity\Client
*/
public function createService(ServiceLocatorInterface $serviceLocator) {
/* #var $clientService \Client\Service\ClientServiceInterface */
$clientService = $serviceLocator->get('Client\Service\Client');
$baseUrl = $serviceLocator->get('Request')->getUri()->getHost();
// client.mydomain.com returns a client entity
// www.mydomain.com doesn't return a client entity
return $clientService->getClientByBaseUrl($baseUrl);
}
}
Related
I'm trying to find out why a field is not saving. It's submitted fine and the page reloads with the same value, but it's not stored in the database. I have this in my project
$contact = new Contact($_POST);
$contact->Save();
However, the Save() function doesn't exist in the Contact class, and it doesn't extend anything! How is it able to call a function that doesn't exist? I don't believe PHP has monkeypatching. I know the function is called because I added print_r($_POST) right above it.
<?php
namespace ArcaSolutions\CoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Contact
*
* #ORM\Table(name="Contact")
* #ORM\Entity(repositoryClass="ArcaSolutions\CoreBundle\Repository\ContactRepository")
* #ORM\HasLifecycleCallbacks
*/
class Contact
{
My new field is defined as
/**
* #var string
*
* #ORM\Column(name="timezone", type="string", length=50, nullable=true)
*/
private $timezone;
/**
* Set timezone
*
* #param string $timezone
* #return Contact
*/
public function setTimezone($timezone)
{
$this->timezone = $timezone;
return $this;
}
/**
* Get timezone
*
* #return string
*/
public function getTimezone()
{
return $this->timezone;
}
It's an eDirectory project based on Symfony 2.8 and PHP 5.6.27.
As Padam87 suggests in the comments, you seem to mix Doctrine 1 with Doctrine 2 syntax. Doctrine 1 uses the Active Record pattern, whereas Doctrine 2 uses the Data Mapper pattern. A nice explaination of the differences can be found here: https://www.culttt.com/2014/06/18/whats-difference-active-record-data-mapper/
A Doctrine 2 entity will never have a save() or similar method. To persist or retrieve entities, you will have to use the entity manager. If you use Symfony, the entity manager can be injected as a service into your controllers or other services.
Read the Doctrine docs on how to work with an entity manager to learn more.
By the way, whatever you’re trying by injecting the $_POST data into your entity – this is a very bad idea. You should first process this data in your controller or some validator and only fill entities with validated content. Also, when using Symfony, you’ll want to get the POST data through the Request object which is passed to your action if you reference it in the signature.
Here’s a stub for a controller which gets the entity manager injected as a dependency (you should also register it the controller as a service in your bundle’s services.yml) and gets the POST data from the Request object:
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityManagerInterface;
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public function someAction(Request $request)
{
$data = $request->request->all();
// validate $data!!!
$contact = new Contact();
$contact->setSomeValue($data["value"]);
$this->entityManager->persist($contact);
$this->entityManager->flush();
return new Response("Ok", 200);
}
In Symfony, again, you could also inject an instance of Symfony\Component\Validator\Validator\ValidatorInterface and use Symfony’s validation component.
I found out why. There were two Contact classes and eDirectory was using the one in edirectory\web\classes\class_Contact.php. The other one I found was in edirectory\src\ArcaSolutions\CoreBundle\Entity\Contact.php. The one it really uses is defined as
class Contact extends Handle {
var $account_id;
...
function Save() {
$this->prepareToSave();
$dbObj = db_getDBObject(DEFAULT_DB,true);;
$sql = "UPDATE Contact SET"
. " updated = NOW(),"
. " first_name = $this->first_name,"
...
So it does have a Save() function.
Hi can I ask about this in laravel framework
namespace Illuminate\Support\Facades;
/**
* #see \Illuminate\Auth\AuthManager
* #see \Illuminate\Contracts\Auth\Factory
* #see \Illuminate\Contracts\Auth\Guard
* #see \Illuminate\Contracts\Auth\StatefulGuard
*/
class Auth extends Facade
{
/**
* Get the registered name of the component.
*
* #return string
*/
protected static function getFacadeAccessor()
{
return 'auth';
}
}
what does the return 'auth' exactly returning to the caller ? is it text 'auth' or an object ? and what is the reason why they only have one method in that class ? I apologize i am just learning oop.
Thank you in advance.
In this case as you see method getFacadeAccessor it's returning auth string.
Facades are just "shortcuts" to use other classes but in fact you shouldn't use them everywhere if you don't need to.
In Laravel you can bind objects/classes into Application. So you can write for example:
$app->bind('something', function() {
return new SomeObject();
});
Let's assume there is method doSomething in SomeObject class.
Now you can use this method using:
$app['something']->doSomething();
But you can also create facade:
class GreatClass extends Facade
{
/**
* Get the registered name of the component.
*
* #return string
*/
protected static function getFacadeAccessor()
{
return 'something';
}
}
and now anywhere in your application you could use:
GreatClass::doSomething();
Answering your question this getFacadeAccessor is returning only the name the name of object that is used when bound to Application. To know how it's used you can look into the source of:
/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php
The method you should look first is getFacadeRoot - because this method is returning the requested object.
Is there a way to extend classes auto-generated from database by Doctrine2 ?
Example: I have this User class generated by Doctrine.
<?php
namespace Entities;
/**
* User
*/
class User
{
/**
* #var integer
*/
private $id;
/**
* #var string
*/
private $firstName;
/**
* #var string
*/
private $lastName;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set firstName
*
* #param string $firstName
*
* #return User
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
return $this;
}
/**
* Get firstName
*
* #return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Set lastName
*
* #param string $lastName
*
* #return User
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
/**
* Get lastName
*
* #return string
*/
public function getLastName()
{
return $this->lastName;
}
I would like to add this function :
public function getFullName()
{
return $this->getFirstName().' '.$this->getLastname();
}
Is there a cleaner way than adding it directly into this class?
I tried to create another class (Test) in libraries and extends it, then add it in autoload (which is working), but i get an error when I try to save object :
class Test extends Entities\User {
public function getFullName() {
return $this->getFirstName().' '.$this->getLastname();
}
}
Message: No mapping file found named 'Test.dcm.yml' for class 'Test'.
I'm using Doctrine2 in CodeIgniter3.
Thanks.
As explained in the Doctrine 2 FAQ:
The EntityGenerator is not a full fledged code-generator that solves all tasks. [...] The EntityGenerator is supposed to kick-start you, but not towards 100%.
In plain English this means you ask Doctrine to generate the Entity files only once. After that, you are on your own and do whatever changes you like (or it needs) to them.
Because an Entity is not just a container for some properties but it's where the entire action happens, this is how the flow should happen, Doctrine cannot write more code for you.
The only way to add functionality to the stub Entities generated by Doctrine is to complete the generated classes by writing the code that implements the functionality of each Entity according to its role in your Domain Model.
Regarding the other issue, on the Test class, the error message is self-explanatory: any class passed to the EntityManager for handling needs to be mapped.
Take a look at the help page about Inheritance Mapping. You can either map class User as a Mapped Superclass (it acts like a template for the derived classes and its instances are not persisted in the database) or you can use Single Table Inheritance to store the instances of all classes derived from User in a single table (useful when they have the same properties but different behaviour).
Or, in case you created class Test just because you were afraid to modify the code generated by Doctrine, put the behaviour you need in class User and drop class Test.
Seems you are having trouble while accessing the user entity class. You mentioned that test is a library class. Why not try to access the User entity class from a controller. If can do this then may be something is wrong with the configuration of test file. Besides, you need to map you doctrine entity class properly. You can have a look here to learn about doctrine mapping using yml: http://doctrine-orm.readthedocs.org/en/latest/reference/yaml-mapping.html
you can do this:
<?php
namespace Entities;
/**
* User
*/
class User extends Test
{
//... and extends Test
}
or
<?php
namespace Entities;
/**
* User
*/
class User
{
//...
public function getFullName() {
return $this->getFirstName().' '.$this->getLastname();
}
}
view more
Symfony 2 - Extending generated Entity class
http://www.theodo.fr/blog/2013/11/dynamic-mapping-in-doctrine-and-symfony-how-to-extend-entities/
http://doctrine-orm.readthedocs.org/en/latest/reference/inheritance-mapping.html
Annotation allows you to specify repository class to add more methods to entity class.
/**
* #ORM\Entity(repositoryClass="App\Entity\UserRepository")
*/
class User
{
}
class UserRepository extends EntityRepository
{
public function getFullName() {
return $this->getFirstName().' '.$this->getLastname();
}
}
// calling repository method
$entityManager->getRepository('User')->getFullName();
Here's a link [http://doctrine-orm.readthedocs.org/en/latest/reference/working-with-objects.html]
7.8.8. Custom Repositories
OK, so now as I eventually decided to use Doctrine2 ORM in my new Zend2 project I have a question about the best design practices to maintain the Model and Entity classes separate. I'm not asking what's the difference between Entity and Model, I understand that. I also have my Service layer connected with Repository classes working just fine. What I'm asking, is a situation when I have a Model class with some business logic, let's say Document class, and then DocumentEntity which represents it's persistence, and just want to keep them separate, so for example, here is my Entity:
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="DocumentRepo")
* #ORM\Table(name="document")
*/
class DocumentEntity {
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="UUID")
* #ORM\Column(type="guid")
*/
protected $guid;
/**
* #ORM\Column(length=64)
*/
protected $name;
// more stuff below...
}
Now, there's my Model class with a lot of business logic that I want to keep separate:
class Document implements SomeImportantInterface, AnotherImportantInterface {
public function doSomeImportantStuff() {
}
public function doEvenMoreImportantStuff() {
}
}
And finally, the Service class:
class DocumentService {
const DOCUMENT_ENTITY = 'DocumentEntity';
/**
* #var EntityManager
*/
protected $em;
/**
* #param EntityManager $entityManager
*/
public function __construct(EntityManager $entityManager) {
$this->em = $entityManager;
}
public function getDocument($guid) {
$documentEntity = $this->em->getRepository(self::DOCUMENT_ENTITY)->findByGuid($guid);
return; //what? I want here Document to be returned, not the DocumentEntity..
}
public function createDocument() {
return new Document();
}
public function saveDocument(Document $document) {
// Document -> DocumentEntity
// $documentEntity = ...?
//$this->em->persist($entityDocument);
//$this->em->flush();
}
}
So as you can see, the plan is to have a Document objects that the application only cares about (accessible via Service), not the DocumentEntities. Two possible approaches that came to my mind:
keep the DocumentEntity as a property inside the Document
make Document to extend DocumentEntity
Or, maybe I'm just missing something in here, and just taking the wrong end of the stick? Looking forward to hear your opinions!
Your entity should extend the model class. Your application needs to do all it's model interaction via a repository interface.
DomainModel
DocumentDomainModel
DocumentDomainModelInterface
DocumentDomainModelRepositoryInterface (get/create/save)
DoctrineEntity
DocumentDoctrineEntity extends DocumentDomainModel
DocumentDoctrineRepository implements DocumentDomainModelRepositoryInterface
This also gives you the flexibility to implement other repositories such as in memory one for testing.
im new to Zf2, i recently upgraded from zf1 and need help and advice on this problem.
Here the fact :
I'm working on medical project (which is an upgrade to a zf1 version) in some controller (page) i need to have the patient's info and current visitation in sidebar panel...
I know i'm new to zf2 but i don't want to do redundant things like having in every action the getvisiteService() and patientService() retrieve info and passing these results to view over and over.
I thought about a plugin but again i have to pass from controller to view and supercharge my view with partials and placeholder helper (grr!!!)
Thinkin' about Strategy and eventlistener but i don't know how these work and i need to inject result to a partial.
So there is a simple and/or complicated way to achieve that? Thank you in advance any hint and code will be appreciated and sorry for my poor english i speak french (such a typical excuse :) )
There's a ton of approaches you could use here, but sticking to your original question, it's quite easy to inject things into your layout model, with something like this:
Module.php
/**
* On bootstrap event
*
* #param \Zend\Mvc\MvcEvent $e
*/
public function onBootstrap(MvcEvent $e)
{
// Inject something, like a nav into your Layout view model
$viewModel = $e->getViewModel(); // Layout View Model
$navigation= new ViewModel(array(
'username' => 'Bob' // Dynamically set some variables..
));
$navigation->setTemplate('navigation/mynav');
$viewModel->addChild($navigation, 'navigation');
}
You could also create a custom view Helper to do the work for you if you wanted
<?php
/**
* MyHelper.php
*/
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use Zend\ServiceManager\ServiceManager;
class MyHelper extends AbstractHelper implements ServiceManagerAwareInterface
{
/**
* Invoke
*
* #return string
*/
public function __invoke()
{
// Dynamically build your nav or what ever.
$patientService = $this->getServiceManager()->get('PatientService');
return 'soemthing';
}
/**
* #var ServiceManager
*/
protected $serviceManager;
/**
* Retrieve service manager instance
*
* #return ServiceManager
*/
public function getServiceManager()
{
return $this->serviceManager;
}
/**
* Set service manager instance
*
* #param ServiceManager $locator
* #return User
*/
public function setServiceManager(ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
return $this;
}
}