php7.0, Phalcon 3.2, MongoDB 3.2.14
I want to connect to MongoDB, but in Phalcon documentation only about connection via MongoClient() and working with it. I have php7.0 and MongoClient() is deprecated in it. How I can correctly use \MongoDB\Driver\Manager() with Phalcon?
In services.php I wrote this:
/**
* MongoDB connection
*/
$di->set( "mongo", function () {
$config = $this->getConfig();
$db_string = sprintf( 'mongodb://%s:%s/%s', $config->mongodb->host, $config->mongodb->port, $config->mongodb->database );
if( isset( $config->mongodb->user ) AND isset( $config->mongodb->password ) ) {
$db_string = sprintf( 'mongodb://%s:%s#%s:%s/%s',
$config->mongodb->user,
(string)$config->mongodb->password,
$config->mongodb->host,
(string)$config->mongodb->port,
$config->mongodb->database );
}
try {
return new \MongoDB\Driver\Manager( $db_string );
} catch (MongoConnectionException $e) {
die( 'Failed to connect to MongoDB '.$e->getMessage() );
}
},
true
);
It works. But in models there are errors. In app/models/User.php I wrote:
use Phalcon\Mvc\Collection;
class User extends Collection
{
public function initialize()
{
$this->setSource('users');
}
}
And in controller:
class IndexController extends ControllerBase
{
public function indexAction()
{
echo User::count();
}
}
In browser I have this:
Call to undefined method ::selectcollection()
#0 [internal function]: Phalcon\Mvc\Collection::_getGroupResultset(Array, Object(User), Object(MongoDB\Driver\Manager))
#1 /var/www/testing/app/controllers/IndexController.php(8): Phalcon\Mvc\Collection::count()
#2 [internal function]: IndexController->indexAction()
#3 [internal function]: Phalcon\Dispatcher->callActionMethod(Object(IndexController), 'indexAction', Array)
#4 [internal function]: Phalcon\Dispatcher->_dispatch()
#5 [internal function]: Phalcon\Dispatcher->dispatch()
#6 /var/www/testing/public/index.php(42): Phalcon\Mvc\Application->handle()
#7 {main}
How I can do it correclty? :) sorry for my English, I from Russia :)
My original question is here.
Use Incubator package: https://github.com/phalcon/incubator
See example of using here -
https://github.com/phalcon/incubator/tree/master/Library/Phalcon/Db/Adapter#mongodbclient
Related
I have the problem to use Slim/Flash/Messages, to do a flash message. I have this error
Fatal error:
Uncaught DI\NotFoundException: No entry or class found for 'Slim\Flash' in C:\laragon\www\cart\vendor\php-di\php-di\src\DI\Container.php:119
Stack trace:
#0 C:\laragon\www\cart\app\container.php(52): DI\Container->get('Slim\\Flash')
#1 [internal function]: DI\Definition\Source\DefinitionFile->{closure}(Object(DI\Container)) #2 C:\laragon\www\cart\vendor\php-di\invoker\src\Invoker.php(82): call_user_func_array(Object(Closure), Array)
#3 C:\laragon\www\cart\vendor\php-di\php-di\src\DI\Definition\Resolver\FactoryResolver.php(81): Invoker\Invoker->call(Object(Closure), Array)
#4 C:\laragon\www\cart\vendor\php-di\php-di\src\DI\Definition\Resolver\ResolverDispatcher.php(58): DI\Definition\Resolver\FactoryResolver->resolve(Object(DI\Definition\FactoryDefinition), Array)
#5 C:\laragon\www\cart\vendor\php-di\php-di\src\DI\Container.php(285): DI\Definition\Resolver\ResolverDispatcher->resolve(Object(DI\Definition\FactoryDefinition), Array)
#6 C:\laragon\www\cart\vendor\php-di\php-di\src\DI\Container.php(122): DI\Contai in C:\laragon\www\cart\vendor\php-di\php-di\src\DI\Container.php on line 119
In the bootstrap/app.php
$container->set('flash', function($container) {
return new \Slim\Flash\Messages($container);
});
in the container.php
Twig::class => function (ContainerInterface $c) {
$twig = Factory::getEngine();
$twig->addExtension(new TwigExtension(
$c->get('router'),
$c->get('request')->getUri()
));
$twig->getEnvironment()->addGlobal('basket', $c->get(Basket::class));
$twig->getEnvironment()->addGlobal('auth', $c->get(Auth::class));
$twig->getEnvironment()->addGlobal('user', $c->get(Customer::class));
$twig->getEnvironment()->addGlobal('flash', $c->get(Flash::class));
return $twig;
},
$twig->getEnvironment()->addGlobal('flash', $c->get(Flash::class)); means that you're looking for a key called Slim\Flash within the container, but you registered it with the key flash.
Therefore change:
$twig->getEnvironment()->addGlobal('flash', $c->get(Flash::class));
to
$twig->getEnvironment()->addGlobal('flash', $c->get('flash'));
Alternatively, you can use the fully qualified class name everywhere:
app.php:
use Slim\Flash\Messages as Flash;
$container->set(Flash::class, function($container) {
return new Flash($container);
});
and add this to the top of container.php:
use Slim\Flash\Messages as Flash;
I get the following error from Owncloud when I try to inject my storage class to my controller.
Request ID: PYpBq4u97OltF80ORglm
Type: OCP\AppFramework\QueryException
Code: 0
Message: Could not resolve storage! Class storage does not exist
File: /var/www/html/lib/private/appframework/utility/simplecontainer.php
Line: 89
Trace
#0 /var/www/html/lib/private/appframework/utility/simplecontainer.php(104): OC\AppFramework\Utility\SimpleContainer->resolve('storage')
#1 /var/www/html/lib/private/appframework/utility/simplecontainer.php(64): OC\AppFramework\Utility\SimpleContainer->query('storage')
#2 /var/www/html/lib/private/appframework/utility/simplecontainer.php(83): OC\AppFramework\Utility\SimpleContainer->buildClass(Object(ReflectionClass))
#3 /var/www/html/lib/private/appframework/utility/simplecontainer.php(104): OC\AppFramework\Utility\SimpleContainer->resolve('OCA\\BusMediaMon...')
#4 /var/www/html/lib/private/appframework/utility/simplecontainer.php(64): OC\AppFramework\Utility\SimpleContainer->query('OCA\\BusMediaMon...')
#5 /var/www/html/lib/private/appframework/utility/simplecontainer.php(83): OC\AppFramework\Utility\SimpleContainer->buildClass(Object(ReflectionClass))
#6 /var/www/html/lib/private/appframework/utility/simplecontainer.php(104): OC\AppFramework\Utility\SimpleContainer->resolve('OCA\\BusMediaMon...')
#7 /var/www/html/lib/private/appframework/app.php(97): OC\AppFramework\Utility\SimpleContainer->query('OCA\\BusMediaMon...')
#8 /var/www/html/lib/private/appframework/routing/routeactionhandler.php(45): OC\AppFramework\App::main('GpsController', 'online', Object(OC\AppFramework\DependencyInjection\DIContainer), Array)
#9 [internal function]: OC\AppFramework\routing\RouteActionHandler->__invoke(Array)
#10 /var/www/html/lib/private/route/router.php(276): call_user_func(Object(OC\AppFramework\routing\RouteActionHandler), Array)
#11 /var/www/html/lib/base.php(882): OC\Route\Router->match('/apps/busmediam...')
#12 /var/www/html/index.php(39): OC::handleRequest()
#13 {main}
In the controller I have:
class GPSController extends Controller {
private $gpsService;
private $busService;
private $appStorage;
public function __construct($AppName, IRequest $request, GPSService $gpsService, BusService $busService, AppStorage $appStorage){
In the application.php I have:
$container->registerService('AppStorage', function($c) {
return new AppStorage(
$c->query('UserStorage'),
$c->query('AppName'),
$c->query('CoreConfig'),
$c->query('UserId'));
});
$container->registerService('UserStorage', function($c) {
return $c->query('ServerContainer')->getUserFolder();
});
and
$container->registerService('GPSController', function($c) {
return new GPSController(
$c->query('AppName'),
$c->query('Request'),
$c->query('GPSService'),
$c->query('BusService'),
$c->query('AppStorage')
);
});
The same storage class is injected into another controller and it works fine there.
What am I doing wrong?
I have checked the official repo of monolog and put together below code, its working great and I am getting response in Slack. But the response are very verbose, How Can i get simple response, without Stack Trace.
And as suggested on doc I have added $monolog->pushProcessor(new WebProcessor($_SERVER)); but its not giving any information about requested URL and server.
class AppServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
if ($this->app->environment('production')) {
// Get The Logger
$monolog = Log::getMonolog();
// **********************************************************************************************
// I have tried official WebProcessor to get url, but its not giving me anything
// **********************************************************************************************
$monolog->pushProcessor(new WebProcessor($_SERVER));
$monolog->pushProcessor(function ($record) {
$record['extra']['session_id'] = Cookie::get(config('session.cookie'));
$record['extra']['request_id'] = Session::get('request_id');
return $record;
});
$slackHandler = new SlackHandler(env('SLACK_TOKEN'), '#sss-sslogs', 'sss-log', true, ':warning:', Logger::ERROR);
// **********************************************************************************************
// Setup Line Formatter but no luck
// **********************************************************************************************
// the default date format is "Y-m-d H:i:s"
$dateFormat = "Y n j, g:i a";
// the default output format is "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n"
$output = "%datetime% > %level_name% > %message% %context% %extra%\n";
// finally, create a formatter
$formatter = new LineFormatter($output, $dateFormat);
$slackHandler->setFormatter($formatter);
$monolog->pushHandler($slackHandler);
}
}
Above code is giving me below response in Slack channel
exception 'Illuminate\Database\Eloquent\ModelNotFoundException' with message 'No query results for model [App\User].' in /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:151
Stack trace:
#0 /home/vagrant/Code/App/app/Http/Controllers/PortfolioController.php(30): Illuminate\Database\Eloquent\Builder->firstOrFail()
#1 [internal function]: App\Http\Controllers\PorofileController->show('users')
#2 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(246): call_user_func_array(Array, Array)
#3 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(162): Illuminate\Routing\Controller->callAction('show', Array)
#4 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(107): Illuminate\Routing\ControllerDispatcher->call(Object(App\Http\Controllers\PortfolioController), Object(Illuminate\Routing\Route), 'show')
#5 [internal function]: Illuminate\Routing\ControllerDispatcher->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#6 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(141): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#7 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#8 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(101): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#9 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(108): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#10 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(67): Illuminate\Routing\ControllerDispatcher->callWithinStack(Object(App\Http\Controllers\PortfolioController), Object(I…
Level
----------------
ERROR
Where is the requested URL and session data??
How can I get only below part with requested URL, I am not interested in Stack trace:
exception 'Illuminate\Database\Eloquent\ModelNotFoundException' with message 'No query results for model [App\User].' in /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:151
I've taken the Doctrine 2 and ZF2 installation, with pagination, and tried to apply a search function to the method.
The album list is accessible via the usual route http://myapp/album
My current code appears to build a usable query using doctrine's createQueryBuilder()
When I give no parameters to title/artist then the result of $qb->getDql(); is SELECT a FROM Album\Entity\Album a and it returns no error and paginated results fine.
My method;
public function indexAction()
{
$view = new ViewModel();
$repository = $this->getEntityManager()->getRepository('Album\Entity\Album');
$qb = $repository->createQueryBuilder('album');
$qb->add('select', 'a')
->add('from', 'Album\Entity\Album a');
if ($this->params()->fromQuery('title')) {
$qb->add('where','title like :title');
$qb->setParameter(':title', '%' . $this->params()->fromQuery('title') . '%');
}
if ($this->params()->fromQuery('artist')) {
$qb->add('where','artist like :artist');
$qb->setParameter(':artist', '%' . $this->params()->fromQuery('artist') . '%');
}
$q = $qb->getDql();
$paginator = new Paginator(new DoctrineAdapter(new ORMPaginator($this->getEntityManager()->createQuery($q))));
$paginator->setDefaultItemCountPerPage(10);
$page = (int)$this->params()->fromQuery('page');
if ($page) $paginator->setCurrentPageNumber($page);
$view->setVariable('paginator', $paginator);
return $view;
}
But when I pass a query through the URL http://myapp/album?title=In%20My%20Dreams the result of $qb->getDql(); is SELECT a FROM Album\Entity\Album a WHERE title like :title which returns the error below.
Zend\Paginator\Exception\RuntimeException
File:
/Users/luke/Sites/hotelio/vendor/zendframework/zendframework/library/Zend/Paginator/Paginator.php:637
Message:
Error producing an iterator
Stack trace:
#0 /myapp/module/Album/view/album/album/index.phtml(20): Zend\Paginator\Paginator->getIterator()
#1 /myapp/vendor/zendframework/zendframework/library/Zend/View/Renderer/PhpRenderer.php(507): include('/myapp...')
#2 /myapp/vendor/zendframework/zendframework/library/Zend/View/View.php(205): Zend\View\Renderer\PhpRenderer->render(Object(Zend\View\Model\ViewModel))
#3 /myapp/vendor/zendframework/zendframework/library/Zend/View/View.php(233): Zend\View\View->render(Object(Zend\View\Model\ViewModel))
#4 /myapp/vendor/zendframework/zendframework/library/Zend/View/View.php(198): Zend\View\View->renderChildren(Object(Zend\View\Model\ViewModel))
#5 /myapp/vendor/zendframework/zendframework/library/Zend/Mvc/View/Http/DefaultRenderingStrategy.php(102): Zend\View\View->render(Object(Zend\View\Model\ViewModel))
#6 [internal function]: Zend\Mvc\View\Http\DefaultRenderingStrategy->render(Object(Zend\Mvc\MvcEvent))
#7 /myapp/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(468): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#8 /myapp/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(207): Zend\EventManager\EventManager->triggerListeners('render', Object(Zend\Mvc\MvcEvent), Array)
#9 /myapp/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php(347): Zend\EventManager\EventManager->trigger('render', Object(Zend\Mvc\MvcEvent))
#10 /myapp/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php(322): Zend\Mvc\Application->completeRequest(Object(Zend\Mvc\MvcEvent))
#11 /myapp/public/index.php(12): Zend\Mvc\Application->run()
#12 {main}
I understand that the error is where the view is accessing the variable, but as the paginator handles the modified query it appears to get as far of the view before erroring. I am not really sure what is going on here.
For the avoidance of doubt, the original method which also operates without error;
public function indexAction()
{
$view = new ViewModel();
$repository = $this->getEntityManager()->getRepository('Album\Entity\Album');
$paginator = new Paginator(new DoctrineAdapter(new ORMPaginator($this->getEntityManager()->createQuery($repository->createQueryBuilder('album')))));
$paginator->setDefaultItemCountPerPage(10);
$page = (int)$this->params()->fromQuery('page');
if ($page) $paginator->setCurrentPageNumber($page);
$view->setVariable('paginator', $paginator);
return $view;
}
I was getting the same error. In my case the problem was "date.timezone" not being set in php.ini. This was causing the following code to actually catch a \DateTime() exception.
Zend\Paginator\Paginator
public function getIterator()
{
try {
return $this->getCurrentItems();
} catch (\Exception $e) {
throw new Exception\RuntimeException('Error producing an iterator', null, $e);
}
}
Apart from bad DQL, "error producing an iterator" can also occur when data/DoctrineORMModule/Proxy does not have the correct write permissions set on it:
chmod 755 data/DoctrineORMModule/Proxy
I'm trying to use Zend Db findBy() magic method, but it gives me this error:
Application error
Exception information:
Message: File "Game.php" does not exist or class "Game" was not found in the file
Stack trace:
#0 C:\Zend\ZendServer\share\ZendFramework\library\Zend\Db\Table\Row\Abstract.php(872): Zend_Db_Table_Row_Abstract->_getTableFromString('Game')
#1 C:\Zend\ZendServer\share\ZendFramework\library\Zend\Db\Table\Row\Abstract.php(1154): Zend_Db_Table_Row_Abstract->findDependentRowset('Game', NULL, NULL)
#2 C:\Zend\Apache2\htdocs\dev.gamenomad.com\application\controllers\GameController.php(125): Zend_Db_Table_Row_Abstract->__call('findGame', Array)
#3 C:\Zend\Apache2\htdocs\dev.gamenomad.com\application\controllers\GameController.php(125): Zend_Db_Table_Row->findGame()
#4 C:\Zend\ZendServer\share\ZendFramework\library\Zend\Controller\Action.php(516): GameController->platformAction()
#5 C:\Zend\ZendServer\share\ZendFramework\library\Zend\Controller\Dispatcher\Standard.php(295): Zend_Controller_Action->dispatch('platformAction')
#6 C:\Zend\ZendServer\share\ZendFramework\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#7 C:\Zend\ZendServer\share\ZendFramework\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#8 C:\Zend\ZendServer\share\ZendFramework\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#9 C:\Zend\Apache2\htdocs\dev.gamenomad.com\public\index.php(26): Zend_Application->run()
#10 {main}
Request Parameters:
array (
'controller' => 'game',
'action' => 'platform',
'x' => '2',
'module' => 'default',
)
Seems like it doesn't detect Game.php even though it exists inside /application/models/DbTable/Game.php
Are there any rules or exceptions I am missing?
This is my code
public function platformAction()
{
// action body
$platform = intval($this->_request->getParam('x'));
$platformTable = new Application_Model_DbTable_Platform();
$xbox360 = $platformTable->find($platform)->current();
//$games = $xbox360->findDependentRowset('Application_Model_DbTable_Game');
$games = $xbox360->findGame();
if(isset($games))
{
if(count($games)>0)
{
foreach($games as $game)
{
echo "{$game->name}<br />";
}
}
}
}