Registering Silex Providers Throwing Errors - service

Creating an App in Silex and trying to take the first few steps, one of which is setting up my services/providers.
I am currently loading these using a YAML file. I have also tried registering each individual like the docs say e.g.
$this->register( new TwigServiceProvider(),array() );
Here is my current bootstrap file(loading services from a file):
<?php
namespace App;
use Igorw\Silex\ConfigServiceProvider;
use Silex\Application as Silex;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\HttpFoundation\Request;
class Bootstrap extends Silex
{
public function __construct()
{
$this['debug'] = true;
$this->registerDefaultParameters();
$this->registerDefaultServices();
$this->registerRoutes();
}
protected function registerDefaultParameters()
{
$paths = isset($this['base_path']) ? $this['base_path'] : array();
if (!isset($paths['base'])) {
$paths['base'] = realpath(__DIR__ . '/../');
}
$defaults = array(
'config' => $paths['base'] . '/App/Config',
'twig.path' => $paths['base'] . '/public/themes/base/templates'
);
foreach ($defaults as $key => $value) {
if (!isset($paths[$key])) {
$paths[$key] = $value;
}
}
$this['paths'] = $paths;
}
protected function registerDefaultServices()
{
$this->register( new ConfigServiceProvider($this['paths']['config'] . "/Services.yml") );
foreach($this['services'] as $serviceName => $serviceData)
{
$this->register( new $serviceData['class'],(array_key_exists('parameters',$serviceData)) ? $serviceData['parameters'] : array() );
}
}
protected function registerRoutes()
{
$this->register( new ConfigServiceProvider($this['paths']['config'] . "/Routes.yml") );
$collection = new RouteCollection();
foreach($this['routes'] as $key => $value)
{
$collection->add( $key, new Route(
$value['path'],
$value['defaults'],
array(),
array(),
null,
null,
$value['methods']
));
}
$this['routes'] = $collection;
}
}
My issue is:
With every provider i am receiving fatal errors like
Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Identifier "this_is_an_identifier" is not defined.'
I'm receiving this errors loading the services from a file and manually. and its different for each provider e.g.
The error related to the twig provider is:
Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Identifier "request_error" is not defined.'
Another one relating to Monolog is :
Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Identifier "dispatcher" is not defined.
So its like every provider/service has something wrong which obviously isn't the case. So my question is why am i continuously receiving these errors? from what i can see im not doing anything wrong?
Heres my composer file just in case it's a version thing:
{
"name": "cranbri/cvcms",
"description": "Cranbri CV CMS Silex",
"minimum-stability": "dev",
"require": {
"silex/silex": "1.2.2",
"symfony/yaml": "2.6.1",
"igorw/config-service-provider": "1.2.2"
},
"autoload": {
"psr-4":{
"App\\": "App/"
}
}
}
This is stopping my development altogether so if anyone can give me any details it will be much appreciated. Cheers

I wasn't calling parent!!! therefore i have none of the values the parent class did hence why many of the $app variables were not set and couldn't be found

Related

MongoDB and Phalcon API

I am trying to connect mongoDB with phalcon API framework.
My code is like below :
index.php file
<?php
if ($handle = opendir('include/models')) {
while (false !== ($entry = readdir($handle))) {
if (preg_match('/\.php$/', $entry)) {
require_once "include/models/$entry";
}
}
closedir($handle);
}
require 'vendor/autoload.php';
use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\Model;
$app = new Phalcon\Mvc\Micro();
$di = new \Phalcon\DI\FactoryDefault();
$config = new Phalcon\Config\Adapter\Ini('include/config/config.ini');
// Simple database connection to localhost
$di->set('mongo', function() {
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
return $manager->selectDb("MyApi");
},true);
$di->set('collectionManager', function () {
return new Phalcon\Mvc\Collection\Manager();
});
$app->setDI($di);
$directory = new User_detail();
$app->get('/userdetail/{code}', function ($code) use ($app,$directory) {
$directory->getUser($app,$code);
});
$app->notFound(function () use ($app) {
$app->response->setStatusCode(424, "Method Failed")->sendHeaders();
echo json_encode(array('status' => 'ERROR', 'messages' => "Method Failed"));
});
$app->handle();
?>
Model file User_detail.php
<?php
use Phalcon\Mvc\Collection;
use Phalcon\Mvc\Model;
use MongoDB\Driver\Manager;
use Phalcon\Mvc\Micro;
use Phalcon\Db\Column;
class User_detail extends Collection
{
public function initialize()
{
$this->setSource("User");
}
function getUser($app,$code)
{
$robot = User_detail::findFirst(
[
[
"Name" => "android",
]
]
);
echo $robot->Name; die;
}
}
?>
I am getting error as
Error: Call to undefined method MongoDB\Driver\Manager::selectDb() in
index.php
What is wrong in it?
First I installed Phalcon incubator using composer into my vendor directory:
composer require phalcon/incubator
Then I make sure that vendor libraries are loaded:
include_once SITE_ROOT . 'vendor/autoload.php';
Then I use \Phalcon\Db\Adapter\MongoDB\Client() found in vendor/phalcon/incubator/Library/Phalcon/Db/Adapter/MongoDB/Client.php
In services.php:
$di->setShared('mongo', function () use ($config) {
$mongo = new \Phalcon\Db\Adapter\MongoDB\Client();
return $mongo->selectDatabase($config->mongodb->dbname);
});
Then ensure my MongoCollection extends \Phalcon\Mvc\MongoCollection (vendor/phalcon/incubator/Library/Phalcon/Mvc/MongoCollection.php).
models/MyCollectionStats.php:
<?php
namespace Common\Models;
class MyCollectionStats extends \Phalcon\Mvc\MongoCollection
{...
For php7 you need to use MongoCollection and other related classes from incubator.

Catching syntax error and custom error reporting

I am using slim framework 3 . I am new to this framework. I am working on catching the errors and returning the custom JSON error and message.
I used this code to catch notFoundHandler error :
$container['notFoundHandler'] = function ($c) {
return function ($request, $response) use ($c) {
return $c['response']
->withStatus(404)
->withHeader('Content-Type', 'application/json')
->write('Page not found');
};
};
But I am able to catch the normal syntax error.
It is showing Warning: fwrite() expects parameter 2 to be string, array given in X-api\controllers\Products.php on line 42
Instead of this message, I want my custom error to handle syntax error reporting.
I used this also,
$container['phpErrorHandler'] = function ($c) {
return function ($request, $response, $exception) use ($c) {
//Format of exception to return
$data = [
'message' => "hello"
];
return $container->get('response')->withStatus($response->getStatus())
->withHeader('Content-Type', 'application/json')
->write(json_encode($data));
};
};
But not working for me.
The default error handler can also include detailed error diagnostic information. To enable this you need to set the displayErrorDetails setting to true:
$configuration = [
'settings' => [
'displayErrorDetails' => true,
],
];
$c = new \Slim\Container($configuration);
$app = new \Slim\App($c);
Note this is not appropriate for production applications, since it may reveal some details you would want not to reveal. You can find more in Slim docs.
EDIT
If you need to handle parseErrors, then you need to define phpErrorHandler in your container, just like you did define notFoundHandler.
$container['phpErrorHandler'] = function ($container) {
return function ($request, $response, $error) use ($container) {
return $container['response']
->withStatus(500)
->withHeader('Content-Type', 'text/html')
->write('Something went wrong!');
};
};
Note: this will work with PHP7+ only, because in older versions parseErrors cannot be catched.
I have used this short of code in my dependencies.php
$container['errorHandler'] = function ($c) {
return function ($request, $response) use ($c) {
$data = [
'message' => "Syntex error"
];
return $c['response']
->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write(json_encode($data));
};
};
set_error_handler(function ($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) {
// This error code is not included in error_reporting, so ignore it
return;
}
throw new \ErrorException($message, 0, $severity, $file, $line);
});
Now its working for me.

ZF2 application - Dispatch error event triggered every time

I'am working on a Zend Framework 2 application and have a strange behavior concerning error handling. My code in Module.php:
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$eventManager->attach(\Zend\Mvc\MvcEvent::EVENT_ROUTE, [$this, 'onPreRoute'], 100);
$eventManager->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH_ERROR, [$this, 'handleError']);
}
public function onPreRoute(MvcEvent $e)
{
$serviceManager = $e->getTarget()->getServiceManager();
$router = $serviceManager->get('router');
$router->setTranslator($serviceManager->get('translator'));
}
public function handleError(MvcEvent $e)
{
$error = $e->getParam('error');
file_put_contents('error.log', $error . PHP_EOL, FILE_APPEND);
switch($error) {
case 'error-router-no-match':
$router = $e->getRouter();
$url = $router->assemble([], ['name' => 'home']);
header('Location: ' . $url);
exit;
}
}
As you can see I'am translating the routes. This works fine. But on every request the dispatch error event is triggered too. The error.log file will be created every time. But the redirect will be only performed if the route doesn't really exist. I think it depends on the translator or is my code in Module.php not correct?
Resolved!
The reason was that the browser automatically requests /favicon.ico and that was not available :-)

Slim 3 blackholing errors

I have a small slim 3 app, and when I throw an exception slim simply shows the generic error message:
Slim Application Error
A website error has occurred. Sorry for the temporary inconvenience.
In slim 2 you can do something like this to turn on debug mode giving you backtraces etc:
$app->config('debug', true);
In slim 3 there doesn't seem to be one. Additionally, it seems to be overriding my exception and error handlers.
How can I get slim to spit out errors, or at least to call my error handlers (Which pipe the output to kint for debug information)
Looking through the source, it's possible to initialize slim 3 with error display like so:
$app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);
I'm not sure if it's possible to change this setting after the fact without replacing the errorHandler altogether.
To show full stack trace on default exception handler use what j-v said.
If you want to handle exceptions in Slim yourself then you need to override Slim's default exception handler as it will be used before your "not in Slim" error handler:
$app = new \Slim\App();
$container = $app->getContainer();
$container['errorHandler'] = function(ServerRequestInterface $request, ResponseInterface $response, Exception $exception) {
//Handle exception here
}
Error handling is rather well documented: Official Docs
$app = new \Slim\App();
$c = $app->getContainer();
$c['errorHandler'] = function ($c) {
return function ($request, $response, $exception) use ($c) {
return $c['response']->withStatus(500)
->withHeader('Content-Type', 'text/html')
->write('Something went wrong!');
};
};
Error handling is best solution to this. You can do something like to see Error Trace
$app = new \Slim\App();
$container = $app->getContainer();
$container['phpErrorHandler'] = $container['errorHandler'] = function ($c) {
return function ($request, $response, $exception) use ($c) {
return $c['response']->withStatus(500)
->withHeader('Content-Type', 'text/html')
->write('Something went wrong!<br><br>' .
nl2br($error->getTraceAsString()));
};
};
Make displayErrorDetails->true.
You will find cause of error.
$config = ['settings' => [
'addContentLengthHeader' => true,
'displayErrorDetails' => true
]];
$app = new \Slim\App($config)

[Symfony\Component\Debug\Exception\ContextErrorException]

I'm making fixtures and when I try to load them I have an error. The relationship between Award and Movie is unidirectional, so I load first Award because it hasn't any reference. The error says:
[Symfony\Component\Debug\Exception\ContextErrorException] Warning: spl_object_hash()
expects parameter 1 to be object, array given in
/Users/benatespina/Development/filmboot.web/vendor/doctrine/mongodb-odm/lib/Doctrine/ODM‌/MongoDB/UnitOfWork.php line 1706.
This is my Fixture class:
namespace MyProject\MovieBundle\DataFixtures\MongoDB;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use MyProject\MovieBundle\Document\Award;
class Awards extends AbstractFixture implements OrderedFixtureInterface {
public function load(ObjectManager $manager) {
$awards = array(
array(
"name" => "Sitges",
"year" => "1992",
"category" => "Best director"
);
foreach ($awards as $i => $award) {
$document = new Award();
$document->setName ($award["name"]);
$document->setYear ($award["year"]);
$document->setCategory($award["category"]);
$manager->persist($document);
$this->addReference("award-" . $i, $award);
}
$manager->flush();
}
public function getOrder() {
return 1;
}
}
This exception has nothing to do with symfony2 or doctrine-fixtures - it's a generic PHP exception.
You are trying to use a variable $i that has never been defined in your addReference() call.
$this->addReference("award-" .$i, $award);