Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do I need to use "readonly" in "FetchTask.php" when "main.php" contains several "$urls" in my case ??? #187

Open
chegmarco1989 opened this issue Sep 20, 2023 · 1 comment
Labels

Comments

@chegmarco1989
Copy link

chegmarco1989 commented Sep 20, 2023

Hello.

I have a blocking function named getDetails that gets contents from different urls.

So, here is my main.php code:

<?php

require __DIR__ . '/../vendor/autoload.php';

use Amp\Future;
use Amp\Parallel\Worker;
use function Amp\async;

$urls = [
    'https://website1.net',
    'https://website2.org',
    'https://website3.com',
];

$executions = [];
foreach ($urls as $url) {
    // FetchTask is just an example, you'll have to implement
    // the Task interface for your task.
    $executions[$url] = Worker\submit(new FetchTask($url));
}

// Each submission returns an Execution instance to allow two-way
// communication with a task. Here we're only interested in the
// task result, so we use the Future from Execution::getFuture()
$responses = Future\await(array_map(
    fn (Worker\Execution $e) => $e->getFuture(),
    $executions,
));

foreach ($responses as $url => $response) {
    \printf("Read %d bytes from %s\n", \strlen($response), $url);
}

When that FetchTask.php file should contain:

use Amp\Cancellation;
use Amp\Parallel\Worker\Task;
use Amp\Sync\Channel;

class FetchTask implements Task
{
    public function __construct(
        private readonly string $url,
    ) {
    }

    public function run(Channel $channel, Cancellation $cancellation): string
    {
        return getDetails($this->url); // Example blocking function
    }
}

Does that FetchTask should normally content readonly in its controller knowing that main.php contains several $urls ???

What could be correct FetchTask.php content in case main.php contains several $urls knowing that I use readonly ???

Thanks to answer me.

@trowski
Copy link
Member

trowski commented Nov 26, 2023

Your code is creating a new instance of FetchTask for each URL in main.php, so readonly on the constructor is fine. This would be the recommended way to use tasks – a new instance each time you submit a task to a worker.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

2 participants