Standalone Laravel queue does not work - php

I am trying to use Laravel queue package outside of Laravel with the database driver, but I got an error with resolving namespaces.
Value of $concrete is 'db'.
$reflector = new ReflectionClass($concrete);
Exception message:
Fatal error: Uncaught exception 'ReflectionException' with message 'Class db does not exist' in ..vendor\illuminate\container\Container.php on line 736
ReflectionException: Class db does not exist in ..vendor\illuminate\container\Container.php on line 736
I am using the illuminate DB package also, and it is working fine, but this one throws exception.

Need resolve DB connection manually and add this connection to Queue manager
Grab mysql connection from DB manager:
$connection = Capsule::schema()->getConnection();
$container = new Container();
Grab Queue manager instance:
$manager = $queue->getQueueManager();
Resolve connection:
$resolver = new \Illuminate\Database\ConnectionResolver(['default' => $connection]);
Add connection to Queue manager:
$manager->addConnector('database', function () use ($resolver) {
return new DatabaseConnector($resolver);
});
Done!
Also need add Illuminate Encryptionn package
Complete code:
<?php
/**
* Created by PhpStorm.
* User: Dmitry
* Date: 05.08.2015
* Time: 19:32
*/
require_once "../vendor/autoload.php";
require_once '../db/db_inc.php'; // DB Capsule config
use Illuminate\Container\Container;
use Illuminate\Queue\Capsule\Manager as Queue;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Queue\Connectors\DatabaseConnector;
$connection = Capsule::schema()->getConnection();
$queue = new Queue();
$queue->addConnection([
'driver' => 'database',
'table' => 'jobs', // Required for database connection
'connection' => 'default',
'host' => 'localhost',
'queue' => 'default',
]);
$queue->getContainer()->bind('encrypter', function() {
return new \Illuminate\Encryption\Encrypter('1111111111111111');
});
$queue->getContainer()->bind('request', function() {
return new \Illuminate\Http\Request();
});
$manager = $queue->getQueueManager();
$resolver = new \Illuminate\Database\ConnectionResolver(['default' => $connection]);
$manager->addConnector('database', function () use ($resolver) {
return new DatabaseConnector($resolver);
});
$queue->setAsGlobal();
Queue::push('SomeJobClass', ['parameters']);

Related

How to use Lumen/Laravel custom service

Im new to Lumen, I have managed to create and register the following ArangoDB service provider along with the service below and got it to work, but Im confused how I actually use them in another service or helper.
registered the provider in bootstrap/app.php
$app->register(App\Providers\ArangoServiceProvider::class);
ArangoServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ArangoServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton('ArangoService', function ($app) {
return new ArangoService($app);
});
}
public function boot()
{
//
}
}
ArangoService.php
<?
namespace App\Services;
use ArangoDBClient\Collection as ArangoCollection;
use ArangoDBClient\CollectionHandler as ArangoCollectionHandler;
use ArangoDBClient\Connection as ArangoConnection;
use ArangoDBClient\ConnectionOptions as ArangoConnectionOptions;
use ArangoDBClient\DocumentHandler as ArangoDocumentHandler;
use ArangoDBClient\Document as ArangoDocument;
use ArangoDBClient\Exception as ArangoException;
use ArangoDBClient\Export as ArangoExport;
use ArangoDBClient\ConnectException as ArangoConnectException;
use ArangoDBClient\ClientException as ArangoClientException;
use ArangoDBClient\ServerException as ArangoServerException;
use ArangoDBClient\Statement as ArangoStatement;
use ArangoDBClient\UpdatePolicy as ArangoUpdatePolicy;
class ArangoService{
public function __construct() {
$connectionOptions = [
// database name
ArangoConnectionOptions::OPTION_DATABASE => 'dbname',
// server endpoint to connect to
ArangoConnectionOptions::OPTION_ENDPOINT => 'tcp://123456789',
// authorization type to use (currently supported: 'Basic')
ArangoConnectionOptions::OPTION_AUTH_TYPE => 'Basic',
// user for basic authorization
ArangoConnectionOptions::OPTION_AUTH_USER => 'root',
// password for basic authorization
ArangoConnectionOptions::OPTION_AUTH_PASSWD => 'passwd',
// connection persistence on server. can use either 'Close' (one-time connections) or 'Keep-Alive' (re-used connections)
ArangoConnectionOptions::OPTION_CONNECTION => 'Keep-Alive',
// connect timeout in seconds
ArangoConnectionOptions::OPTION_TIMEOUT => 3,
// whether or not to reconnect when a keep-alive connection has timed out on server
ArangoConnectionOptions::OPTION_RECONNECT => true,
// optionally create new collections when inserting documents
ArangoConnectionOptions::OPTION_CREATE => true,
// optionally create new collections when inserting documents
ArangoConnectionOptions::OPTION_UPDATE_POLICY => ArangoUpdatePolicy::LAST,
];
// turn on exception logging (logs to whatever PHP is configured)
ArangoException::enableLogging();
$connection = new ArangoConnection($connectionOptions);
$collectionHandler = new ArangoCollectionHandler($connection);
$handler = new ArangoDocumentHandler($connection);
}
public function main(){
print "hello world!<br/>";
}
}
This all above works, but how do I in a controller, call a service, lets call it "UsersService" that has functions like GetUser() , how does this "UsersService" use the $connection, $collectionHandler and $handler , that I have created in my ArangoDB service.
route pointing to a controller (got that one)
controller calling UsersService
UsersService using the arango service and passing something back to the controller
grateful for any help!

Enabling Sentry on Symfony console program without the whole symfony being installed

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);

Target [Illuminate\Contracts\Debug\ExceptionHandler] is not instantiable

I'm using Eloquent in combination with Slim Framework to build a small API. For some reason, I am getting this error, and I can't locate the problem:
Target [Illuminate\Contracts\Debug\ExceptionHandler] is not instantiable.
Database settings are correct. This error is thrown in my staging environment on the server. Locally, with MySQL 5.6.29, it works perfectly. Although I don't think it's related to MySQL 5.7 because I have another app running on the same server with the same version of Eloquent.
Can anyone point me in the right direction?
I'm using:
Eloquent Version: 5.3.23
PHP Version: 5.6.28
Database Driver & Version: MySQL 5.7.16
Backtrace
/path/to/app/shared/vendor/illuminate/container/Container.php:644
Illuminate\Container\Container -> make
/path/to/app/shared/vendor/illuminate/database/Connectors/ConnectionFactory.php:130
call_user_func
/path/to/app/shared/vendor/illuminate/database/Connection.php:964
Illuminate\Database\Connection -> getPdo
/path/to/app/shared/vendor/illuminate/database/Connection.php:832
Illuminate\Database\Connection -> reconnectIfMissingConnection
/path/to/app/shared/vendor/illuminate/database/Connection.php:717
Illuminate\Database\Connection -> run
/path/to/app/shared/vendor/illuminate/database/Connection.php:350
Illuminate\Database\Connection -> select
/path/to/app/shared/vendor/illuminate/database/Query/Builder.php:1648
Illuminate\Database\Query\Builder -> runSelect
/path/to/app/shared/vendor/illuminate/database/Query/Builder.php:1634
Illuminate\Database\Query\Builder -> get
/path/to/app/shared/vendor/illuminate/database/Eloquent/Builder.php:632
Illuminate\Database\Eloquent\Builder -> getModels
/path/to/app/shared/vendor/illuminate/database/Eloquent/Builder.php:327
Illuminate\Database\Eloquent\Builder -> get
/path/to/app/shared/vendor/illuminate/database/Eloquent/Builder.php:297
Illuminate\Database\Eloquent\Builder -> first
...
I'm suspecting it has something to do with an unregistered error handler:
github link
But how can I register the custom error handler when not using Laravel?
The solution of #patricus can be implemented as follows:
// bootstrap Eloquent ORM
$container = new Container();
$container->singleton(
'Illuminate\Contracts\Debug\ExceptionHandler'
, 'My\Custom\DatabaseExceptionHandler'
);
$factory = new ConnectionFactory( $container );
$connection = $factory->make([
'driver' => 'mysql'
, 'host' => App::config( 'database_host' )
, 'database' => App::config( 'database_name' )
, 'username' => App::config( 'database_user' )
, 'password' => App::config( 'database_password' )
, 'charset' => App::config( 'database_charset' )
, 'collation' => App::config( 'database_collate' )
, 'prefix' => ''
]);
$resolver = new ConnectionResolver();
$resolver->addConnection( 'default', $connection );
$resolver->setDefaultConnection( 'default' );
// initialize connection
Model::setConnectionResolver( $resolver );
You should be able to access the container to register your own exception handler through the capsule.
$capsule = new \Illuminate\Database\Capsule\Manager();
$capsule->getContainer()->singleton(
\Illuminate\Contracts\Debug\ExceptionHandler::class,
\Your\ExceptionHandler\Implementation::class
);
If you want a real quick, very dumb, exception handler, you can use this:
class DumbExceptionHandler implements \Illuminate\Contracts\Debug\ExceptionHandler
{
public function report(Exception $e)
{
//
}
public function render($request, Exception $e)
{
throw $e;
}
public function renderForConsole($output, Exception $e)
{
throw $e;
}
}
NB: untested. I believe this should work looking at the code.
In my case it was permissions issue of system user who executes php command.
Please make sure that your xampp server and the database server is working and running.

Phalcon's universal class loader can't find my class

As a total php and phalcon newbie, I'm trying to use the recommended universal class loader using this code:
$loader = new \Phalcon\Loader();
// Register some directories
$loader->registerDirs(
array(
"php/assistants/"
)
);
// register autoloader
$loader->register();
$test = new dbAssistant();
as I understand I have to reffer to the php file as a class what I have inside of php/assistants/dbAssistant.php is the following code, trying to connect to a database:
<?php
function connect() {
$connection = new Phalcon\Db\Adapter\Pdo\Mysql(array(
'host' => 'localhost',
'username' => 'root',
'password' => 'tt',
'dbname' => 'testdb',
'port' => '3306'
));
echo 'Connected!!!';
}
again what I understand is that I have to refer to dbAssistant.php as a class and that's why I'm using $test = new dbAssistant();, but it gives me the following error:
Fatal error: Class 'dbAssistant' not found in /var/www/html/test/test.php on line 18
I know that it seeme normal, but the strange thing is that if I remove the connect() function and place the code out of it, I can see the Connected!!! echo, but it is followed by the same(above) error. I know that I'm missing something really small here, but as a complete php newbie, I really can't spot the problem.
Can you give me a push?
php/assistants/dbAssistant.php is not a class but a plain Php file. There should be a class in there with the name dbAssistant.
class dbConnect {
public function connect() {
///Do your stuff
}
}

What settings should I use for db if I only want to use MongoDB in PhalconPHP?

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#

Categories