I have this plain console program:
namespace MyApp\Console;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
class MaConsole extends Command {
protected function configure()
{
$this->setDescription('Console\'s not console');
}
protected function execute(
\Symfony\Component\Console\Input\InputInterface $input,
\Symfony\Component\Console\Output\OutputInterface $output
) {
$output->writeln('Doing Stuff');
}
}
And I load it like that:
namespace MyApp;
use Symfony\Component\Console\Application as SymfonyApplication;
use MyApp\Console\MaConsole;
class Application extends SymfonyApplication
{
public function __construct(
string $name = 'staff',
string $version = '0.0.1'
) {
parent::__construct($name, $version);
throw new \Exception('Test Sentry on Playground');
$this->add(new MaConsole());
}
}
And I want to log the exception thrown above in Sentry service. So I my entrypoint is:
use MyApp\Application;
require __DIR__ . '/vendor/autoload.php';
Sentry\init([
'dsn' => getenv('SENTRY_DSN'),
'environment' => getenv('ENVIRONMENT')
]);
$application = (new Application())->run();
But I fail to log the error into sentry, even thouhg I have set the correct enviromental variables.
The application does not load the Full Symfony framework, but instead it uses the console only components so I have no idea if I should use the Sentry Symfony Integration: https://docs.sentry.io/platforms/php/symfony/
The reason why is because I do not know how in my case to load the bundle, therefore I use the SDK.
Edit 1:
I also tried to catch the exception and manually log it but form some reason is not logged as well:
use MyApp\Application;
require __DIR__ . '/vendor/autoload.php';
try {
Sentry\init([
'dsn' => getenv('SENTRY_DSN'),
'environment' => getenv('ENVIRONMENT')
]);
throw new \Exception('Test Sentry on Playground');
$application = (new Application())->run();
} catch(Exception $e) {
Sentry\captureException($e);
}
You can use the dispatcher :
use Symfony\Component\EventDispatcher\EventDispatcher;
$dispatcher = new EventDispatcher();
$dispatcher->addListener(ConsoleEvents::ERROR, function (ConsoleErrorEvent $event) use ($env) {
Sentry\init([
'dsn' => getenv('SENTRY_DSN'),
'environment' => $env
]);
Sentry\captureException($event->getError());
});
$kernel = new AppKernel($env, $debug);
$application = new Application($kernel);
$application->setDispatcher($dispatcher);
$application->run($input);
Related
I have just created slim 4 project using "composer create-project slim\slim-skeleton appdb". I have a routes.php as
<?php
declare(strict_types=1);
use App\Application\Actions\User\ListUsersAction;
use App\Application\Actions\User\ViewUserAction;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\App;
use Slim\Interfaces\RouteCollectorProxyInterface as Group;
return function (App $app) {
$app->post('/hello', function (Request $request, Response $response) {
$response->getBody()->write('Hello world!');
return $response;
});
};
and the index.php as
<?php
declare(strict_types=1);
use App\Application\Handlers\HttpErrorHandler;
use App\Application\Handlers\ShutdownHandler;
use App\Application\ResponseEmitter\ResponseEmitter;
use DI\ContainerBuilder;
use Slim\Factory\AppFactory;
use Slim\Factory\ServerRequestCreatorFactory;
require __DIR__ . '/../vendor/autoload.php';
// Instantiate PHP-DI ContainerBuilder
$containerBuilder = new ContainerBuilder();
if (false) { // Should be set to true in production
$containerBuilder->enableCompilation(__DIR__ . '/../var/cache');
}
// Set up settings
$settings = require __DIR__ . '/../app/settings.php';
$settings($containerBuilder);
// Set up dependencies
$dependencies = require __DIR__ . '/../app/dependencies.php';
$dependencies($containerBuilder);
// Set up repositories
$repositories = require __DIR__ . '/../app/repositories.php';
$repositories($containerBuilder);
// Build PHP-DI Container instance
$container = $containerBuilder->build();
// Instantiate the app
AppFactory::setContainer($container);
$app = AppFactory::create();
$callableResolver = $app->getCallableResolver();
// Register middleware
$middleware = require __DIR__ . '/../app/middleware.php';
$middleware($app);
// Register routes
$routes = require __DIR__ . '/../app/routes.php';
$routes($app);
/** #var bool $displayErrorDetails */
$displayErrorDetails = $container->get('settings')['displayErrorDetails'];
// Create Request object from globals
$serverRequestCreator = ServerRequestCreatorFactory::create();
$request = $serverRequestCreator->createServerRequestFromGlobals();
// Create Error Handler
$responseFactory = $app->getResponseFactory();
$errorHandler = new HttpErrorHandler($callableResolver, $responseFactory);
// Create Shutdown Handler
$shutdownHandler = new ShutdownHandler($request, $errorHandler, $displayErrorDetails);
register_shutdown_function($shutdownHandler);
// Add Routing Middleware
$app->addRoutingMiddleware();
// Add Error Middleware
$errorMiddleware = $app->addErrorMiddleware($displayErrorDetails, false, false);
$errorMiddleware->setDefaultErrorHandler($errorHandler);
// Run App & Emit Response
$response = $app->handle($request);
$responseEmitter = new ResponseEmitter();
$responseEmitter->emit($response);
Attempts to access post route as 127.0.0.1/appdb/public/hello/Peter, gives an error
{ "statusCode": 404, "error": { "type": "RESOURCE_NOT_FOUND", "description": "Not found." } }
What am I doing wrong?
Thanks in advance
I'm using the Symfony router component. The router tells you if a defined route match with an incoming request and return you an array with the infomartion of that route(in my case I have defined a controller and method). I wanna know which is the best practice to execute that method. Right now I'm doing something like this:
<?php
require 'vendor/autoload.php';
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\HttpFoundation\Request;
$routes = new RouteCollection();
$routes->add('test', new Route(
'/test/{id}',
['_controller' => 'app\controllers\testController::test'],
['id' => '[0-9]+'],
[],
'',
[],
['GET']
)
);
$context = new RequestContext();
$context->fromRequest(Request::createFromGlobals());
$matcher = new UrlMatcher($routes, $context);
try {
$parameters = $matcher->match($context->getPathInfo());
call_user_func_array($parameters['_controller'], array_slice($parameters, 1, -1));
} catch (ResourceNotFoundException $e) {
echo $e->getMessage();
}
?>
This works but I don't know if this is the correct way to do it.
I'm doing some programming in Silex with the symfony components and I think I have found a bug with the symfony/serializer and the symfony/validator components.
First let me explain what I'm traing to achieve, then let's go to the code.
My objective is to annotate a class with information like serialization directives as well as validation directives. As the reading of these annotations can cost a litle cpu, I like to cache them in memory. For this purpose, I'm using memcache wrapper in the Doctrine/Common/Cache package.
The problem I face is that both the symfony/serializer and the symfony/validator write Metadata to the cache using the class name as key. When they try to retrieve the metadata later, they throw an exception, because the cache has invalid metadata, either an instance of Symfony\Component\Validator\Mapping\ClassMetadata or Symfony\Component\Serializer\Mapping\ClassMetadataInterface.
Following is a reproductible example (sorry if its big, I tried to make as small as possible):
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
class Foo
{
/**
* #var int
* #Assert\NotBlank(message="This field cannot be empty")
*/
private $someProperty;
/**
* #return int
* #Groups({"some_group"})
*/
public function getSomeProperty() {
return $this->someProperty;
}
}
use Doctrine\Common\Annotations\AnnotationReader;
use \Memcache as MemcachePHP;
use Doctrine\Common\Cache\MemcacheCache as MemcacheWrapper;
$loader = require_once __DIR__ . '/../vendor/autoload.php';
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$loader, 'loadClass']);
$memcache = new MemcachePHP();
if (! $memcache->connect('localhost', '11211')) {
throw new \Exception('Unable to connect to memcache server');
}
$cacheDriver = new MemcacheWrapper();
$cacheDriver->setMemcache($memcache);
$app = new \Silex\Application();
$app->register(new Silex\Provider\SerializerServiceProvider());
$app['serializer.normalizers'] = function () use ($app, $cacheDriver) {
$classMetadataFactory = new Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory(
new Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader(new AnnotationReader()), $cacheDriver);
return [new Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer($classMetadataFactory) ];
};
$app->register(new Silex\Provider\ValidatorServiceProvider(), [
'validator.mapping.class_metadata_factory' =>
new \Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory(
new \Symfony\Component\Validator\Mapping\Loader\AnnotationLoader(new AnnotationReader()),
new \Symfony\Component\Validator\Mapping\Cache\DoctrineCache($cacheDriver)
)
]);
$app->get('/', function(\Silex\Application $app) {
$foo = new Foo();
$app['validator']->validate($foo);
$json = $app['serializer']->serialize($foo, 'json');
return new \Symfony\Component\HttpFoundation\JsonResponse($json, \Symfony\Component\HttpFoundation\Response::HTTP_OK, [], true);
});
$app->error(function (\Exception $e, \Symfony\Component\HttpFoundation\Request $request, $code) {
return new \Symfony\Component\HttpFoundation\Response('We are sorry, but something went terribly wrong.' . $e->getMessage());
});
$app->run();
After running this example you get fatal errors.
Can anyone confirm that I'm not making a hard mistake here?
Currently my workaround for this is rewrite the DoctrineCache class making use of a namespace for the cache keys. Its working, but I think its ugly.
I think what you need to do is two separate CacheDrivers. See https://github.com/doctrine/cache/blob/master/lib/Doctrine/Common/Cache/CacheProvider.php for how namespaces are used there.
You could:
$validatorCacheDriver = new MemcacheWrapper();
$validatorCacheDriver->setMemcache($memcache);
$validatorCacheDriver->setNamespace('symfony_validator');
$serializerCacheDriver = new MemcacheWrapper();
$serializerCacheDriver->setMemcache($memcache);
$serializerCacheDriver->setNamespace('symfony_serializer');
// note that the two drivers are using the same memcache instance,
// so only one connection will be used.
$app['serializer.normalizers'] = function () use ($app, $serializerCacheDriver) {
$classMetadataFactory = new Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory(
new Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader(new AnnotationReader()), $serializerCacheDriver);
return [new Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer($classMetadataFactory) ];
};
$app->register(new Silex\Provider\ValidatorServiceProvider(), [
'validator.mapping.class_metadata_factory' =>
new \Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory(
new \Symfony\Component\Validator\Mapping\Loader\AnnotationLoader(new AnnotationReader()),
new \Symfony\Component\Validator\Mapping\Cache\DoctrineCache($validatorCacheDriver)
)
]);
I've trimmed the code to only show the parts that play some part in the solution. I hope this helps!
I have a custom Silex\RouteCollection which I want to register...
class RouteCollectionProvider extends RouteCollection
{
public function __construct() {
$this->add(
'Index',
new Route('/', array(
'method' => 'get',
'controller' => 'index',
'action' => 'index'
)
));
}
}
...during the bootstrapping:
$app = new Silex\Application();
/** here **/
$app->run();
I could use:
$app = new Silex\Application();
$routes = new RouteCollectionProvider();
foreach ($routes->getIterator() as $route) {
$defaults = $route->getDefaults();
$pattern = $route->getPath();
$callback = 'Controller\\'
. ucfirst($defaults['controller'])
. 'Controller::'
. $defaults['action']
. 'Action';
$app->get($pattern, $callback);
}
$app->run();
I don't like having the initialization of those routes right in there.
Do you know any spot in Silex, where this does fit better?
I cannot use $app->register() because it's getting called too late and the routes won't get active in there.
Maybe there is an event I can use with
$app->on('beforeCompileRoutesOrSomething', function() use ($app) {
// initialize routes
}
Or a hook in the Dispatcher?
My aim is to not have a big collection of $app->get() or $app->post() in there. I also know I can ->mount() a controller but then still I have all my get definitions in my bootstrap and not in a Provider.
This post solves the problem: Scaling Silex pt. 2.
$app = new Application;
$app->extend('routes', function (RouteCollection $routes, Application $app) {
$routes->addCollection(new MyCustomRouteCollection);
return $routes;
});
$app->run();
I created a simple Phalcon project using Phalcon DevTools (1.2.3).
Now I want to use MongoDB for the database. How do I set this up correctly?
I came this far (see code below):
This is my config.php
<?php
return new \Phalcon\Config(array(
'database' => array(
'adapter' => 'Nosql', //Was 'Mysql', but Nosql is not supported?
'host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'test',
),
'application' => array(
'controllersDir' => __DIR__ . '/../../app/controllers/',
'modelsDir' => __DIR__ . '/../../app/models/',
'viewsDir' => __DIR__ . '/../../app/views/',
'pluginsDir' => __DIR__ . '/../../app/plugins/',
'libraryDir' => __DIR__ . '/../../app/library/',
'cacheDir' => __DIR__ . '/../../app/cache/',
'baseUri' => 'localhost/',
)
));
This is my services.php
<?php
use Phalcon\DI\FactoryDefault,
Phalcon\Mvc\View,
Phalcon\Mvc\Url as UrlResolver,
//Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter, //Do I need this when I use Mongo?
Phalcon\Mvc\View\Engine\Volt as VoltEngine,
Phalcon\Mvc\Model\Metadata\Memory as MetaDataAdapter,
Phalcon\Session\Adapter\Files as SessionAdapter;
/**
* The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
*/
$di = new FactoryDefault();
/**
* The URL component is used to generate all kind of urls in the application
*/
$di->set('url', function() use ($config) {
$url = new UrlResolver();
$url->setBaseUri($config->application->baseUri);
return $url;
}, true);
/**
* Setting up the view component
*/
$di->set('view', function() use ($config) {
$view = new View();
$view->setViewsDir($config->application->viewsDir);
$view->registerEngines(array(
'.volt' => function($view, $di) use ($config) {
$volt = new VoltEngine($view, $di);
$volt->setOptions(array(
'compiledPath' => $config->application->cacheDir,
'compiledSeparator' => '_'
));
return $volt;
},
'.phtml' => 'Phalcon\Mvc\View\Engine\Php'
));
return $view;
}, true);
/**
* Database connection is created based in the parameters defined in the configuration file
*/
$di->set('mongo', function() use ($config) {
$mongo = new Mongo();
return $mongo->selectDb($config->database->dbname);
});
/**
* If the configuration specify the use of metadata adapter use it or use memory otherwise
*/
$di->set('modelsMetadata', function() {
return new MetaDataAdapter();
});
/**
* Start the session the first time some component request the session service
*/
$di->set('session', function() {
$session = new SessionAdapter();
$session->start();
return $session;
});
I altered the standard mysql db connection to be mongo, using the documentation.
But now I have to set up my database adapter in Config, but Nosql doesn't seem to work. DevTools throws this error in the terminal when trying to create a model:
Error: Adapter Nosql is not supported
When I do put in ' Mysql' for the adapter in the config and try to create a model, this is the error I get:
Error: SQLSTATE[HY000] [2002] No such file or directory
Does it need the Mysql adapter to be set in order to use Mongo/Nosql? Or should I put in something else for the adapter/config? Any ideas?
within service.php file where you have mongo service registered
$di->set('mongo', function() {
$mongo = new Mongo();
return $mongo->selectDb("DB_NAME");
}, true);
below that put following lines of code,
$di->set('collectionManager', function(){
return new Phalcon\Mvc\Collection\Manager();
}, true);
After the above is done you need to ensure that your model is extending from \Phalcon\Mvc\Collection
E.g. Customers.php
class Customers extends \Phalcon\Mvc\Collection
{
public $name;
public $email;
}
Once above is done, you can verify if everything is working fine as follows
$robot = new Customers();
$robot->email= "abc#test.com";
$robot->name = "XYZ";
if ($robot->save() == false)
{
echo "Could not be Saved!!";
}
else
{
echo "Data Saved!!";
}
You can put above code in any Controller-Action and try.
If everything goes well, you should be able to see one document created within Customer collection within your database of MongoDB.
Refer http://docs.phalconphp.com/en/latest/reference/odm.html for more..
$di->set('mongo', function() {
$user = 'blog';
$password = 'blog';
$host = 'localhost';
$port = '27017';
$db = 'blog';
$cn = sprintf('mongodb://%s:%d/%s',$host,$port,$db);
$con = new Mongo($cn,array('username'=>$user,'password'=>$password));
return $con->selectDB($db);
}, true);
As of the latest PhalconPHP, MongoDB seems to be a supported option for cache only, not for using as a replacement for the database.
It looks there is no MongoDB adapter for the Config component, only MySQL and couple of others (text based) in the incubator (https://github.com/phalcon/incubator).
You can still use MongoDB for the ACL and your Models though, see https://github.com/phalcon/incubator/tree/master/Library/Phalcon/Acl/Adapter and http://docs.phalconphp.com/en/latest/reference/odm.html#