Do I need to use "readonly" in "FetchTask.php" when "main.php" contains several "$urls" in my case ???
chegmarco1989 opened this issue · 1 comments
chegmarco1989 commented
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 commented
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.