Laravel - calling method without user request - php

I have my own library class which is designed for gathering data from external web sites (uses curl). This class has constructor which receives parameters (e.g. URL, xpaths) and method updateDatabase. How to pass parameters to constructor and call method updadeDatabase in app internally? This method should be fired e.g. two times per day without user request (using the cron) So I don't want insert this code in controller and create appropriate route. How to do this?
class Source
{
public function __construct(Http $http, array $params)
{
...
}
public function updateDatabase()
{
...
}
}

Your best bet is probably to create an artisan command. This gives you access to to run your code within the Laravel framework from the command line (or cron job).
All the information you need for creating an artisan command can be found here.
Basically, inside the command's fire() method you would do something like:
public function fire() {
$source = App::make('Source'); // or however you instantiate your class
$source->updateDatabase();
// output a message to the command line
$this->info('All done.');
}
Your command can also take arguments and options from the command line, if you need to pass those in.
The documentation linked above will tell you all you need to know.

Related

Global service objects in Laravel

I have a service file that processes data and stores it in private fields. Many queries are executed, hence I'd like to instantiate the service file only once and access data from the fields when necessary in later stages of the request's lifecycle.
I've tried registering the service file in Laravel's service provider using the following snippet, but it did not seem to work as I expected.
$this->app->singleton('App\Services\UserService', function ($app) {
return new App\Services\UserService();
});
In my case, the first time I called the service methods was in my middleware class. The particular methods I called should've set many private fields in place which I could later use. Service file was loaded in using the "injection" method.
public function __construct(UserService $user_service) {
$this->user_service = $user_service;
}
However, once the request finally proceeded to the controller method, the fields in the service object had been nulled and I had to call the "heavy" methods once again.
Within the the controller constructor method, I resolved the service file using the resolve() helper method, however I don't think that would've made a difference.
Is there something I've missed or misunderstood?
Any help or pointers are appriciated!

Test functionality in the Job Class

I like to test (Feature test via phpunit) some methods in the Job Class (Lumen Queue) to make sure it is working correctly.
Problem is Job Class have some jobs methods like $this->job->getJobId() and $this->release(5);
If I run phpunit from console, I get an error:
Error: Call to a member function getJobId() on null
The test code look like this:
/**
* #test
*/
public function it_has_successfully_uploaded()
{
$job = new SomeJob(['file' => ['file1.zip']]);
$job->handle();
}
How do I solve this issue?
Your code is using $this->job->getJobId(), but nowhere is that property declared or set. Are you perhaps using the InteractsWithQueue trait but forgot to include that in your code paste?
If so, the job property is set in InteractsWithQueue::setJob. This method may be called from several places, but in your case it is probably from Illuminate\Queue\CallQueuedHandler::setJobInstanceIfNecessary. This is some internal initialization of your job that Laravel does for you, which you must imitate in your test setup.
I would implement a simplistic version of Illuminate\Contracts\Queue\Job and call $job->setJob(new SimplisticVersionShazaamJob(...)); before calling $job->handle().

How to set up a cron job with codeigniter

I am trying to set up a cron job using COdeigniter but I cannot figure out how to get it to work. I have a file called email_check.php in my controllers folder, and I have added a .cron file to the servers cron folder, which contains the following
email_check.cron
*/1 * * * * php /var/www/html/application/controllers/email_check
email_check.php
class Email_check extends CI_Controller {
function __construct()
{
parent::__construct();
$this->index();
}
function index()
{
$this->load->model('admin/info_model');
$this->info_model->addTestData();
}
}
The addTestData adds a new row into a database table. I would like this to run every minute, however it isn't working at all and I have no idea why.
Maybe it may be the paths that are wrong. Do I need to point the php part to the php.exe in the server.
If anyone could help or point me in the right direction it would be greatly appreciated!
To use CodeIgniter via the commmand line, you need to call the index.php file and pass in the controller and method as arguments, plus any other arguments. So at the minimum the cron job call would be:
~/public_html/sitefolder/index.php controller method
Or using the path to your application index file. But, you also need to use PHP compiled for the command line, not just PHP for CGI-FCGI. So your call might be something like:
/ramdisk/bin/php5-cli ~/public_html/sitefolder/index.php controller method
Depending on where your PHP CLI is located.
This won't work because just hitting your email_check.php controller won't do anything because its not going to call your index() method.
You want to either write a script that is going to create a new instance of the controller and call the method or call it via a URL, something like this I think
* * * * * wget http://sitename.com/email_check

Symfony2: Call a Controller /File on EVERY action

I'm doing a huge project with Symfony2. Frontend is javascript/html5 canvas. For site changes I use ajax requests.
Now I want to call a php file which should be executed with EVERY user action. Is there an elegant way to do so?
For better understanding: I'm doing some kind of game and the php checks, if something happend (recruitments done, buildings finished etc.).
Take a look into JMSAopBundle
If by user action you mean executing a controller action (i.e. server side), what I would do is listen to the kernel.controller event: http://symfony.com/doc/current/book/internals.html
so you can load your script and execute it juste before the target controller is invoked
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
public function onKernelController(FilterControllerEvent $event)
{
$controller = $event->getController();
//...
// call your php file here
// the controller can be changed to any PHP callable
$event->setController($controller);
}
I don't think you even need to modify the controller so you can remove the first and last line...

Access shell methods in controller? Cake PHP 1.3

I wrote a shell method in CakePHP 1.3 that has a return value.
I'd like to be able to access that method from within a controller, so that I can pass its return value into the View.
I'm not sure how to access those methods appropriately from within the controller. Have I done it wrong?
I could easily duplicate the code, but I'd like to "keep it DRY", and the actual functionality, I believe, doesn't belong with this particular controller - I just need it's return value in this particular view.
EDIT:
I realize I'm sort of asking the wrong question here, since the Shell itself shouldn't necessarily return a value. I've changed the code so that the Shell is only using the return value I want, and now I wonder - what is the appropriate place for extra classes/code that needs to be accessed from a Shell and a Controller?
It seems like Component code, but I'm not sure how to access Components from the Shell. It's not a Plugin, as I understand them. Where does this go?
In one of the projects we imported shell tasks, ex:
App::import('Core', 'Shell');
App::Import('Vendor','shells/tasks/sometask');
$returndata = TasknameTask::execute($somevalue);
You can create a component to do that.E.g
/* in app/controllers/components */
class ShellComponent extends Object
{
function do_shell()
{
return shell_exec('some command');
}
}
Then use it in any controller you want as below
/* in some controller*/
var $components = array('Shell','maybe some other components',....);
function testShell()
{
$result = $this->Shell->do_shell();
....
}
Shells shouldn't directly return a value explicitly, they ought to report it somehow, e.g. by echoing it to stdout, logging to a file or sending an email for example. I like to think of shells as controllers for the cli.
Without knowing your application, my suggestion would be to see if you could refactor the logic in your current shell into a model class or something like that, have the model method return the value, then use that model in your shell. This way, you can also use that model in your controller.
The accepted answer doesn't seems to work for Cake 2.0
For Cake 2.0
if (!class_exists('Shell')) {
require CONSOLE_LIBS . 'shell.php';
}
App::import('Shell', 'DoSomething');
DoSomethingShell::main();
Bear in mind some Shell method doesn't work in this mode, such as $this->out, so more hacking is required.

Categories