PHP Doctrine relationship with namespaces - php

i just started using PHP namespaces. I have two models classes in separate files
In both files first i declare namespace
namespace eu\ed\sixImport\importViewer\models;
first class:
class Log extends \Doctrine_Record
$this->hasMany('eu\ed\sixImport\importViewer\models\DataSource as DataSource', array(
'local' => 'id',
'foreign' => 'logId'));//setup relationship in setUp method
second class:
class DataSource extends \Doctrine_Record
$this->hasOne('eu\ed\sixImport\importViewer\models\Log as Log', array(
'local' => 'logId',
'foreign' => 'id'));//setup relationship in setUp method
Everything works fine untill i make something like this
$query = \Doctrine_Query::create()
->select('log.*')
->from('eu\ed\sixImport\importViewer\models\Log log')
->leftJoin("log.DataSource")
->orderBy("log.id DESC");
$requiredPage = (($startingRow - ($startingRow%$rowsRequired))/$rowsRequired) + 1;
$pager = new \Doctrine_Pager($query, $requiredPage, $rowsRequired);
$res = $pager->execute();
$this->logsPageCount = $pager->getNumResults();
print_r($res[0]["DataSource"]->toArray());//it fails on access to relationship
Than Doctrine throw Exception
Uncaught exception 'Doctrine_Exception' with message 'Couldn't find class eu\ed' in C:\wamp\www\importViewer\resources\doctrine\Doctrine-1.1.5\lib\Doctrine\Table.php:293...
From Exception, you can see, it looks for class 'eu\ed'. Backslash[s] cut the rest of the class name, and than class is not obviously found. Can you give me some suggestion, how to solve this problem?
Thanks

I am not sure if Doctrine 1 supports namespaces. I really recommend using Doctrine 2 - it is built on top of mature architecture (with API from Java Hibernate) and does not involve that much magic like Doctrine 1.

Related

How to get a list of services programmatically in Symfony?

I want to have a list of services and class names in my web application. I can use this command in console:
php bin/console debug:container
And I get something like this:
Symfony Container Public Services
=================================
-------------------------------------------------------------------- --------------------------------------------------------------------------------------------
Service ID Class name
-------------------------------------------------------------------- --------------------------------------------------------------------------------------------
annotation_reader Doctrine\Common\Annotations\CachedReader
app.annotations.softdelete.driver AppBundle\Doctrine\SoftDelete\Mapping\Driver\Annotation
app.annotations.translate.driver AppBundle\Doctrine\Mapping\Driver\TranslateDriver
app.be_auth_controller.listener AppBundle\EventListener\BeAuthControllerListener
I want to have this information on a web page using Symfony 3.
I created a service and I used:
$this->container->getServiceIds();
which returns something like:
[
0 => "service_container"
1 => "annotation_reader"
2 => "annotations.reader"
3 => "app.annotations.softdelete.driver"
4 => "app.annotations.translate.driver"
...
]
I don't know, how to get the class names.
In any cases works this:
get_class($this->container->get($this->container->getServiceIds()[1]))
But in some other cases it throws different exceptions.
To get full definition of given service you can use ContainerBuilder and Symfony cache file.
first create instance of ContainerBuilder:
$container = new ContainerBuilder();
then load cache file:
$cachedFile = $this->container->getParameter('debug.container.dump');
$loader = new XmlFileLoader($container, new FileLocator());
$loader->load($cachedFile);
now you can get full definition of your service like this:
$definition = $container->getDefinition('service_name')
$definition->getClass();
Your attempt with get_class is what came to mind as I was reading it, but whatever errors you are getting will come from improper fetching of those services. After all when you call $container->get(...), its at that moment instantiating those classes.
To be honest the output you are looking to replicate can be reproduced based on the method used by that command.
https://github.com/symfony/framework-bundle/blob/master/Command/ContainerDebugCommand.php
You'll just need to adapt it to work for you.

Multiple Controllers Zend Framework 2 - Entity Manager Doctrine 2

I am using Zend Framework 2.2.2 and Doctrine2 Module 0.7.0.
My goal is to have my functions related to a task in a standalone php-class. My current workflow is between two different programms: get data -> modify and store data -> send data.
This workflow needs functions from 3 ZF2 modules:
1. source software module
2. internal storage mechanism module
3. destination software module
The first task is successfull but when I move my data to the second module like this (shrinked to the main code):
use MTNewsletterEngine\Controller\NewsletterEngineController;
/** #var \MTNewsletterEngine\Controller\NewsletterEngineController */
private $_newsletterEngine;
$this->_newsletterEngine = new NewsletterEngineController();
[...]
$this->_newsletterEngine->addNewNewsletterRecipient($emailAddresses,1);
The second Controller has problems getting the service locator:
Fatal error: Call to a member function get() on a non-object in C:\xampp\htdocs\app\trunk\module\MTNewsletterEngine\src\MTNewsletterEngine\Controller\NewsletterEngineController.php on line 51
Line 51:
$em_mtnewsletterengine = $this->getServiceLocator()->get('doctrine.entitymanager.orm_mtnewsletterengine');
NewsletterEngineController is the Main Controller from Module MTNewsletterEngine.
I am confused as I don't know how to get this solved. Thanks.
Do not create a new instance of NewsletterEngineController by using the new keyword. The ServiceLocator will not be injected to the created object this way. Use Zend\ServiceManager to retrieve an instance of Zend\Mvc\Controller\ControllerManager (alias: "ControllerLoader" (ci)) and use the get method, to load the target controller. Zend\Mvc\Controller\ControllerManager extends the ServiceManager itself (because it is a plugin manager).
Check your module.config.php. The controller should be listed as an invokable controller.
Example:
'controllers' => array(
'invokables' => array(
'MTNewsletterEngine\Controller\NewsletterEngine' => 'MTNewsletterEngine\Controller\NewsletterEngineController'
),
),
$this->_newsletterEngine = $this->getServiceLocator()
->get('ControllerLoader')
->get('MTNewsletterEngine\Controller\NewsletterEngine');
For more information read the manual and try to understand the way the ServiceManager / ServiceLocator (which is part of Zend\Di) works.
Maybe you should also think about the structure of your application. I am not sure what you are trying to do there but it seems like you are mixing up different application layers.
Docs
http://framework.zend.com/manual/2.2/en/index.html#zend-di
http://framework.zend.com/manual/2.2/en/index.html#zend-servicemanager

Doctrine - ModelClassName not found

I am new to doctrine(using version 1.2) and following the steps given in the documentation manual. I've installed and configured it perfectly. But i have a problem while working with models. I have followed each and every step and have successfully generated the models in the models folder.. but after that when i m using the demo code
$user = new User();
$user->username = 'jwage';
$user->password = 'changeme';
it says..
Fatal error: Class 'User' not found in C:\wamp\www\test_doctrine\test.php on line 25
whilst if i check the output of
Doctrine_Core::loadModels('models');
i get
Array
(
[BaseUser] => BaseUser
[User] => User
[UserTable] => UserTable
)
how do i get access to the User class??
Doctrine is not loading the base classes. I had faced a similar problem and I solved it by modifying the autoload function wherein I am getting the base class and I require them then and there itself.
You then in the bootstrap.php file, after spl_autoload_register(array('Doctrine', 'autoload'));, you need to Doctrine_Core::loadModels('models');.
This way the base class gets included through the autoload function and the child class (in this case the User Class) can extend it and then you can access it.

Why doesn't Doctrine 2 find my entities?

I'm trying to learn about using Doctrine 2 by making a very simple script which fetches information from my database. The problem is that I can't find any documentation explaining how Doctrine finds and uses my mapping entities. And so when it complains that it's not finding an entity, I don't know what to do to solve the problem. Consider the following structure in my www folder:
Doctrine/
Entities/
person.php
myTestPage.php
person.php
<?php
/** #Entity #Table(name="person")*/
class person
{
/**
* #Id #Column(type="integer")
*/
protected $uid;
}
?>
myTestPage.php
<?php
require "Doctrine/Doctrine/ORM/Tools/Setup.php";
$lib = "Doctrine";
Doctrine\ORM\Tools\Setup::registerAutoloadDirectory($lib);
use Doctrine\ORM\Tools\Setup,
Doctrine\ORM\EntityManager;
$paths = array("/Entities");
$isDevMode = true;
$dbParams = array("driver" => "pdo_mysql",
"host" => "myhost.ca",
"user" => "Shawn",
"password" => "noneofyourbusiness",
"dbname" => "testDB");
$config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
$em = EntityManager::create($dbParams, $config);
$qb = $em->createQueryBuilder();
$qb->select(array('uid'))
->from('person', 't');
$query = $qb->getQuery();
$result = $query->getResult();
echo $result;
?>
When I visit myTestPage.php, I get the following error message:
Fatal error: Uncaught exception 'Doctrine\ORM\Query\QueryException'
with message '[Semantical Error] line 0, col 24 near 'person':
Error: Class 'person' is not defined.' in
C:\wamp\www\Doctrine\Doctrine\ORM\Query\QueryException.php on line 47
The problem seems to be that Doctrine can't find person.php, but how can I solve this?
I don't exactly know what the "re1_chercheur" means, but when I tried your code, it complained about person not being defined, so i included that and it worked.
Of course, this should be dealt with by using an autoloader of some sort, but I think doctrine has some solution for that also. I haven't been using their autoloader, because I have my own which uses the PSR compliant autoloading.
Also in your select, if you want just the "uid", use "t.uid". "t" is the alias of the person class, so in other places in the query, you'll be using "t" to get to it's properties (you could do a ->where("t.uid = someNumber")). If you want the whole object use select("t");
I found the doctrine documentation quite helpful, just make sure you go in the order it is laid out, and you'll get the hang of it in no time.
I know this is not an exact answer, but maybe it points you into the right direction.

What are the possible reasons for App::import() not working?

I'm trying to implement a simple way to manage static pages in CakePhp, as described in this article.
The problem I'm facing is that App::import() doesn't seem to import the required class in the routes.php file.
The code is the following:
App::import('Model','StaticPage');
$page = new StaticPage();
$slugs = $page->find('list', array(
'fields' => array('StaticPage.slug'),
'order' => 'StaticPage.slug DESC'
));
I'm getting the error: Fatal error: Class 'StaticPage' not found in ...
This class is present in the models folder (models/StaticPage.php).
I just started CakePhp a few weeks ago and I guess I'm missing a simple thing here...
I'm using CakePhp 1.3 and Php 5.2.42.
I think the reason it doesn't work is because you don't follow CakePHP's naming conventions for file names: file names are lowercase and underscored. So renaming your file to static_page.php should fix the problem.
Having taken a quick look at the article you reference, your snippet doesn't match up. You're importing the ClassRegistry class (which doesn't need to be imported) and then trying to instantiate a StaticPage. I'd recommend removing the AppImport reference all together and using ClassRegistry:
$page = ClassRegistry::init( 'StaticPage' );
You don't need the AppImport line because ClassRegistry::init() both loads the model and instantiates the object.
The other (potential) problem I see is that your model file name doesn't follow convention. It should be models/static_page.php. Cake's inflection may not be handling the deviation from the norm.
Like the error says: You are missing the Class StaticPage. Are you sure that you have this file? If you do, sure that it's in right place, has the right filename so the autoloader can find it?.

Categories