peppeocchi / php-cron-scheduler

PHP cron job scheduler
MIT License
811 stars 144 forks source link

No Arguments get passed in function. #101

Closed sitenzo closed 4 years ago

sitenzo commented 4 years ago

Hello All,

i have read the readme and want to use the schedule a function that i have copyd and pasted in my code. I get the following error

PHP Warning: Illegal string offset 'user' in /home//domains//**/automations/Scheduler.php on line 41

My complete file looks like this (where vendor/autoload.php is called in the bootstrap file):

include_once(__DIR__ . '/../app/bootstrap.php');

use GO\Scheduler;

$scheduler = new Scheduler();

$scheduler->call(
    function ($args) {
        return $args['user'];
    },
    [
        'user' => 'test',
    ],
    'myCustomIdentifier'
);

$scheduler->run();

i am on PHP version 7.3 And using php-cron-scheduler version : 3.0

Thanks.

peppeocchi commented 4 years ago

@sitenzo thanks for pointing that out, the documentation is incorrect. All of the arguments you pass in the array as a second argument, will be injected to your function. To give you an example

$scheduler->call(
    function ($firstName, $lastName) {
        echo "The fullname is '{$firstName} {$lastName}'";
    },
    [
        'John',
        'Doe'
    ],
    'myCustomIdentifier'
);
// Output: The fullname is 'Jon Doe'

which is the same as doing

$scheduler->call(
    function ($firstName, $lastName) {
        echo "The fullname is '{$firstName} {$lastName}'";
    },
    [
        'first_name' => 'John',
        'last' => 'Doe',
    ],
    'myCustomIdentifier'
);
// The output will be the same, the keys don't really matter in this case and you can't retrieve arguments by key

If you want to pass an array of key => value you'll have to pass an array within the array of arguments.

$user = new User;
$user->firstName = 'John';
$user->lastName = 'Doe';

$scheduler->call(
    function ($args) {
        echo "The fullname is '{$args['user']->firstName} {$args['user']->lastName}'";
    },
    [
        ['user' => $user]
    ],
    'myCustomIdentifier'
);
// Output: The fullname is 'Jon Doe'

Hope this makes sense, I'll update the readme and close this issue