Need help setting up Doctrine 2 - php

i setup Doctrine 1 b4 but it seems like now when i try Doctrine 2 it fails
i have Doctrine installed at D:\ResourceLibrary\Frameworks\Doctrine
D:\ResourceLibrary\Frameworks\Doctrine\bin
D:\ResourceLibrary\Frameworks\Doctrine\Doctrine
D:\ResourceLibrary\Frameworks\Doctrine\Doctrine\Common
D:\ResourceLibrary\Frameworks\Doctrine\Doctrine\DBAL
D:\ResourceLibrary\Frameworks\Doctrine\Doctrine\ORM
i put D:\ResourceLibrary\Frameworks\Doctrine\bin in the PATH Windows Environment Variable
and added D:\ResourceLibrary\Frameworks\Doctrine to the php.ini include_path
i find that when i try to do
D:\>php doctrine.php
Could not open input file: doctrine.php
fails ... i thought that since i have D:\ResourceLibrary\Frameworks\Doctrine\bin in the PATH Windows Environment Variable, it shld be able to find doctrine.php?
D:\ResourceLibrary\Frameworks\Doctrine\bin>php doctrine.php
Warning: require(D:\ResourceLibrary\Frameworks\Doctrine\bin/../lib/vendor\Symfony\Components\Console\Helper\HelperSet.ph
p): failed to open stream: No such file or directory in D:\ResourceLibrary\Frameworks\Doctrine\Doctrine\Common\ClassLoad
er.php on line 143
Fatal error: require(): Failed opening required 'D:\ResourceLibrary\Frameworks\Doctrine\bin/../lib/vendor\Symfony\Compon
ents\Console\Helper\HelperSet.php' (include_path='D:\ResourceLibrary\Frameworks\ZendFramework\library;D:\ResourceLibrary
\Frameworks\Doctrine;.;c:\php\includes') in D:\ResourceLibrary\Frameworks\Doctrine\Doctrine\Common\ClassLoader.php on li
ne 143
then 2nd try, pass with errors ...

After spending several hours to configure Doctrine 2 on my machine last night I finally succedded to work with Doctrine 2.
I configured Doctrine 2 in this way.
There are several ways to install Doctrine 2 although I preferred to download from package manager.
First I downloaded package DoctrineORM-2.0.0BETA3.tgz from http://www.doctrine-project.org/projects/orm/download
I extracted the tar file inside my test folder where I tested my sample code. My folder looks like
./test
DoctrineORM/
DoctrineORM/bin
DoctrineORM/bin/Doctrine
Then I created 2 folders on root 'model' and 'proxies'.
Now we need to bootstrap Doctrine.
--- Bootsrap ---
<?php
// test.php
require 'DoctrineORM/Doctrine/Common/ClassLoader.php';
$classLoader = new \Doctrine\Common\ClassLoader('Doctrine', 'DoctrineORM');
$classLoader->register(); // register on SPL autoload stack
$classloader = new \Doctrine\Common\ClassLoader('model', __DIR__);
$classloader->register();
$config = new \Doctrine\ORM\Configuration();
$cache = new \Doctrine\Common\Cache\ArrayCache();
$config->setMetadataCacheImpl($cache);
$config->setQueryCacheImpl($cache);
$driverImpl = $config->newDefaultAnnotationDriver('model');
$config->setMetadataDriverImpl($driverImpl);
$config->setProxyDir('proxies');
$config->setProxyNamespace('proxies');
$config->setAutoGenerateProxyClasses(true);
$config->getAutoGenerateProxyClasses();
$connectionOptions = array(
'driver' => 'pdo_mysql',
'dbname' => 'test',
'user' => '[DB_User]',
'password' => '[DB_Pass]'
);
$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);
//echo 'Hello World!' . PHP_EOL;
// Get result from Table
$q = $em->createQuery('SELECT c FROM model\User c ORDER BY c.name');
$t = $q->getResult();
echo "<pre>"; print_r($t);
// Save a new User to DB
$uu = new model\User();
$uu->name = 'test name1';
$uu->age = 4;
$em->persist($uu);
$em->flush();
--- Bootsrap ---
Then I created a model file in model directory
--- Model - User.php ---
<?php
// Model File model/User.php
namespace Model;
/** #Entity #Table(name="users") */
class User
{
/**
* #Id #Column(type="integer")
* #GeneratedValue(strategy="AUTO")
*/
public $id;
/** #Column(type="string", length=50) */
public $name;
/** #Column(type="integer", length=50) */
public $age;
}
--- Model - User.php ---
My complete folder structure now looks like below.
./test
DoctrineORM/
DoctrineORM/bin
DoctrineORM/bin/Doctrine
Model/
Model/User.php
test.php
Hope this will help you. If you need any further help I can send you the complete source which works fine at my machine.

You don't need the entire Symfony framework. Just the bits that Doctrine relies on.
If you download the current version of the ORM component (right now at BETA2), it will include a folder called Symfony (probably in lib/vendor/Symfony, but it tends to move around with new releases). You need to make sure that the ClassLoader in doctrine.php or cli-config.php can find that Symfony folder.
$classLoader = new \Doctrine\Common\ClassLoader('Symfony', __DIR__ . '/path/to/Symfony');
$classLoader->register();
I hope this information is accurate. The Doctrine team keeps messing with the structure of the release they closer they get to a final version.

If you want to use the command line interface in the new Doctrine 2 beta you also have to install the Symfony 2 framework (because it includes the Console Helper) and put it into your include path.
As far as I know there is currently no PEAR installation available, so you will have to download the sources from the Symfony 2 website or via Git.
On a sidenote: It seems that you also tried to execute doctrine.php at a path where it doesn’t exist. That’s the reason why you got the
Could not open input file: doctrine.php
error message.

Doctrine v2.* is stored in bin dir.
Try like this :
$ vendor/bin/doctrine orm:conver-mapping xml src/ --from-database --force
Dont put PHP on start.

Related

How to fix Symfony v2.8 "Creating/Configuring Services in the Container" 'autoloader expected class ...' error

For quite a while I've been trying to understand how to add my own library of functions that I want to use in my Web-App's different controller/bundles, but I just found that I needed to 'house' these functions a Symfony Service Container.
Unlike other computer languages, Services, are not a background process!
To get a better handle on this, I tried out the example in the Symfony v2.8 guide section on Creating/Configuring Services in the Container. I created the following file in the suggested directory:
<?php // <=== This was missing from the MessageGenerator.php file!
//
// Adding it to the file solved the autoloader error, and now the MessageGenerator
// class loads properly!
//
// src/AppBundle/Service/MessageGenerator.php
namespace AppBundle\Service;
class MessageGenerator {
public function getHappyMessage() {
$messages = [
'You did it! You updated the system! Amazing!',
'That was one of the coolest updates I\'ve seen all day!',
'Great work! Keep going!'
];
$index = array_rand($messages);
return $messages[$index];
}
}
Then I added the following to the services configuration file:
# app/config/services.yml
services:
app.message_generator:
class: AppBundle\Service\MessageGenerator
arguments: []
And then I placed the following lines in a controller/bundle that otherwise was previously working:
$messageGenerator = $this->container->get( 'app.message_generator' );
$generatedMessage = $messageGenerator->getHappyMessage();
When I uploaded these files and ran the associated web-page, I got:
The autoloader expected class "AppBundle\Service\MessageGenerator" to be defined in
file "/var/www/vhosts/symfony2/vendor/composer/../../src/AppBundle/Service/
MessageGenerator.php". The file was found but the class was not in it, the class name
or namespace probably has a typo.
This message appears to be saying that the MessageGenerator.php file was found in the src/AppBundle/Service directory. However the class MessageGenerator was not defined in the MessageGenerator.php file because the file wasn't recognised as a php file due to the missing
The MessageGenerator.php file was missing
$messageGenerator = $this->container->get( 'app.message_generator' );
$generatedMessage = $messageGenerator->getHappyMessage();
lines were executed, and $generatedMessage contained one of the array element messages, as expected.

Phalcon 2 vs Phalcon 3 instantiate model

I've migrated my Phalcon project from 2 to 3 and get some unexpected behavior. In my loader I do this:
<?php
use Phalcon\Loader;
$loader = new Loader();
$loader->registerDirs(
array(
$config->application->libraryDir,
$config->application->controllersDir,
$config->application->modelsDir
)
);
$loader->register();
Now, when I try to instantiate one of my models in my controller-action the code halts:
$present = new \Present();
Results in a "recv() failed (104: Connection reset by peer) while reading response header from upstream" error in /var/log/nginx/error.log.
However, when I instantiate the class directly in my loader.php file the model is auto-loaded and I can instantiate it anywhere. The workaround for the controller action is:
if (class_exists('Present')) { // THIS triggers the autoloader
$present = new \Present();
$present->save();
}
So the issue is solved for now. My question is: why doesn't
new \Present()
trigger the auto-loader in the controller-action as I expected? Why did it work under Phalcon 2? Why does it work when I do it directly in the loader.php or in public/index.php?

Phalcon MVC model Exception

I'm trying to create an API with Phalcon for the first time.
I have been followed the tutorial "http://docs.phalconphp.com/en/latest/reference/tutorial-rest.html", but encountered a problem.
I've been created a new project with all the settings, and inside I got:
a "models" folder with "photos.php" file
a "index.php" with connection to my DB and function to retrieve information from "photos" table
The problem is that when I'm trying to activate the function through the browser i get an Error:
"Phalcon\Mvc\Model\Exception: Model 'photos' could not be loaded inC:\wamp\www\Test\index.php on line 77".
$photos = $app->modelsManager->executeQuery($phql); // line 77
What can cause this problem?
It's one of three problems:
1 - Your class name in photos.php is not photos.
2 - You have mis-referenced the photos model in your PHQL query.
3 - You have not registered the directory where your models are stored. To do this, add
$loader = new \Phalcon\Loader();
$loader->registerDirs(array(
'/path/to/models'
))->register();
after
$di = new \Phalcon\DI\FactoryDefault();
but before
$app = new \Phalcon\Mvc\Micro();
If you create project structure using Phalcon developer tool, the config.ini might need an update like this:
from:
modelsDir = /models/
to:
modelsDir = **..**/models/
i just faced same issue, got it solved by add require with model path right after $di = new \Phalcon\DI\FactoryDefault(); and
before $app = new \Phalcon\Mvc\Micro($di);
like suggested by brian

Using FirePHP with Zend Framework 2

I'm trying to use FirePHP with Zend Framework 2, but there seems to be something missing. Here's the basic code I'm trying to run:
$writer = new Zend\Log\Writer\FirePhp();
$logger = new Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('FirePHP logging enabled');
The error I get is "FirePHP Class not found". I was initially puzzled because I do have a FirePhp class in my Zend/Log/Writer folder. But then I saw that the class constructor requires a FirePhp\FirePhpInterface object. So I checked the Zend/Log/Writer/FirePhp folder and there's a FirePhpBridge class in there that implements FirePhpInterface, but it also requires a FirePHP instance in the constructor. I don't have any FirePHP.php file in my Zend/Log/Writer/FirePhp folder. Am I supposed to get this from somewhere else?
Update
I now have managed to get FirePHP working, but I'm trying to figure out how to do it in a clean way so this works. The only way I've gotten it to work is putting it in the root directory of my project and doing the following:
include_once('FirePHP.php');
$writer = new Zend\Log\Writer\FirePhp(new Zend\Log\Writer\FirePhp\FirePhpBridge(FirePHP::getInstance(true)));
$logger = new Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('FirePHP logging enabled');
I assume that normally I should be able to create a writer like so:
$writer = new Zend\Log\Writer\FirePhp();
However, where this goes wrong I believe is in the getFirePhp() function of the Zend\Log\Writer\FirePhp class. The class does this:
if (!$this->firephp instanceof FirePhp\FirePhpInterface
&& !class_exists('FirePHP')
) {
// No FirePHP instance, and no way to create one
throw new Exception\RuntimeException('FirePHP Class not found');
}
// Remember: class names in strings are absolute; thus the class_exists
// here references the canonical name for the FirePHP class
if (!$this->firephp instanceof FirePhp\FirePhpInterface
&& class_exists('FirePHP')
) {
// FirePHPService is an alias for FirePHP; otherwise the class
// names would clash in this file on this line.
$this->setFirePhp(new FirePhp\FirePhpBridge(new FirePHPService()));
}
This is where I get lost as to how I'm supposed to set things up so that this class_exists('FirePHP') call finds the right class and new FirePHPService() also works properly.
First you should add this code to Module.php of your module
return array(
//...
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
);
and here content of autoload_classmap.php
<?php
return array(
'FirePHP' => realpath(APPLICATION_PATH . '/vendor/FirePHP').'/FirePHP.php',
);
FirePHP.php(renamed from FirePHP.class.php) downloaded from official site.
then you can write below code in any place of your module and it will work
use Zend\Log\Writer\FirePhp;
use Zend\Log\Logger;
$writer = new FirePhp();
$logger = new Logger();
$logger->addWriter($writer);
$logger->info("hi");
Am I supposed to get this from somewhere else?
Yes, you need to get FirePHP into your project and autoloading.
If you're using composer (and I recommend that you do), just add:
"firephp/firephp-core" : "dev-master"
(or similar) in your composer.json and update. If you're not using composer, you should grab the firephp libs, and let your autoloader know about them.

How to integrate Doctrine 2 and Zend Framework 1.12 in a module based application

I've been looking for an explanation on how to integrate Doctrine 2 and Zend Framework 1.12 (or 1.11, or another --I don't really know whether it matters or not but what I'm using is 1.12). I could find several blog posts and even solved questions right here in Stack Overflow but after read them one and all, I couldn't get to get what I was after: do it in a modular application. So, I'd be very grateful if somebody could give me the keys to achieve this.
Thank you very much!
EDIT:
Thank you guys for your replies but the recent release of ZF2 made me to decide to leave ZF1 in order to take advantage of all new improvements and features. As #KTastrophy said, integrating ZF and Doctrine is quite much easier now (I'd even dare to say that everything is easier and more consistent with ZF2). Thank you one more time!
It's easy to integrate doctrine 2 with ZF using the doctrine PEAR installation. After installing you just need to put this in your bootstrap:
protected function _initDoctrine() {
require_once "Doctrine/ORM/Tools/Setup.php";
\Doctrine\ORM\Tools\Setup::registerAutoloadPEAR();
$options = $this->getOptions();
$loader = new \Doctrine\Common\ClassLoader('YourNamespace', realpath(APPLICATION_PATH . "/../library"));
$loader->register();
$isDevMode = (APPLICATION_ENV == 'production') ? false: true;
$entityManager = \Doctrine\ORM\EntityManager::create(
$options['doctrine']['dbal'],
\Doctrine\ORM\Tools\Setup::createYAMLMetadataConfiguration(array(
realpath(APPLICATION_PATH."/../library/YourNamespace/Yaml"),
), $isDevMode)
);
Zend_Registry::set('entityManager', $entityManager);
return $entityManager;
}
The $this->getOptions() retrieves the database name, user and password from the config file.
If you take this tutorial as an example
http://christian.soronellas.es/2010/12/19/zend-framework-and-doctrine-2/?lang=en
See this part of the configuration code
$config = new Configuration();
$config -> setMetadataCacheImpl($cache);
$driverImpl = $config -> newDefaultAnnotationDriver($options['entitiesPath']);
$config -> setMetadataDriverImpl($driverImpl);
$config -> setQueryCacheImpl($cache);
$config -> setProxyDir($options['proxiesPath']);
$config -> setProxyNamespace('Application\Models\Proxies');
$config -> setAutoGenerateProxyClasses(('development' == APPLICATION_ENV));
$em = EntityManager::create( $this -> _buildConnectionOptions($options), $config );
The function newDefaultAnnotationDriver actually takes an array of entitites path. This creates the opportunity for you to get creative. When I found out about this, I simply created an entity folder in each module and pass each path along the newDefaultAnnotationDriver parameter in an array. Ofcourse by doing this, you will need to set the namespace per module.
I use Bisna
You should apply this patch https://github.com/guilhermeblanco/ZendFramework1-Doctrine2/pull/45
And that works well for me.
In the controller I have this function for retrieve the Entity Manager
/**
* Retrieve the Doctrine Container.
*
* #return Doctrine\ORM\EntityManager
*/
public function getEntityManager()
{
return $this->getInvokeArg('bootstrap')->getResource('doctrine')->getEntityManager();
}

Categories