Use closures inside a class
igorlealantunes opened this issue · 3 comments
Crunz version: 2.0+
PHP version: 7.4.9
Operating system type and version: MAC OSX
Description
I am trying to run my tasks inside a class function (instead of plain PHP scripts). And I'm getting errors related to class namespaces (some internal classes of the library cannot access the class that I am using to wrap the call to the closure inside the run() method of the scheduler object ).
How to reproduce
Try to call the run() method of the schedule object inside a class.
Possible Solution
Remove the dependencies between the closure function passed into the run() method and the parent class.
Additional context
Example of usage with classes:
<?php
namespace Services\Cron_jobs;
/**
* Organize each cron job inside a class
*/
class Test_task
{
function __construct()
{
$this->schedule = new \Crunz\Schedule();
}
public function run() # each class of type "task" will have a run method (we can create interfaces or abstract class to ensure the contract)
{
$task = $this->schedule->run(function() {
file_put_contents("test.txt", "Testing only");
});
$task
->everyMinute()
->description('Testing only');
return $this->schedule;
}
}
return (new Test_task())->run(); # returns an instance of \Crunz\Schedule(); as required by the library
Hello, do you use Composer and Crunz shares autoloader with your app?
Hi Pablo, thanks for the support.
I am using Composer to install Crunz, but the autoloader is not the same of my app.
Could you try to somehow "merge" autoloaders and then test? Looks like issue is not with Crunz but with autoloader.