{"id":13616580,"url":"https://github.com/spatie/fork","last_synced_at":"2025-05-13T22:05:23.421Z","repository":{"id":46076160,"uuid":"360546768","full_name":"spatie/fork","owner":"spatie","description":"A lightweight solution for running code concurrently in PHP","archived":false,"fork":false,"pushed_at":"2025-04-24T08:58:23.000Z","size":90,"stargazers_count":953,"open_issues_count":1,"forks_count":79,"subscribers_count":15,"default_branch":"main","last_synced_at":"2025-04-29T21:39:20.520Z","etag":null,"topics":["async","concurrent","performance","php"],"latest_commit_sha":null,"homepage":"https://spatie.be/open-source","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/spatie.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"spatie"}},"created_at":"2021-04-22T14:24:23.000Z","updated_at":"2025-04-24T08:58:26.000Z","dependencies_parsed_at":"2024-12-19T20:00:33.641Z","dependency_job_id":"4a15ac54-2159-498c-b87f-65cc1a486e3f","html_url":"https://github.com/spatie/fork","commit_stats":{"total_commits":131,"total_committers":13,"mean_commits":"10.076923076923077","dds":"0.48091603053435117","last_synced_commit":"b6f180a259026c45ae0dfe1ab047fb3206cb9a62"},"previous_names":[],"tags_count":17,"template":false,"template_full_name":"spatie/package-skeleton-php","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Ffork","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Ffork/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Ffork/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Ffork/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spatie","download_url":"https://codeload.github.com/spatie/fork/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254036817,"owners_count":22003653,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["async","concurrent","performance","php"],"created_at":"2024-08-01T20:01:30.462Z","updated_at":"2025-05-13T22:05:18.570Z","avatar_url":"https://github.com/spatie.png","language":"PHP","readme":"# A lightweight solution for running PHP code concurrently\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/fork.svg?style=flat-square)](https://packagist.org/packages/spatie/fork)\n[![Tests](https://github.com/spatie/fork/actions/workflows/run-tests.yml/badge.svg)](https://github.com/spatie/fork/actions/workflows/run-tests.yml)\n[![GitHub Code Style Action Status](https://img.shields.io/github/workflow/status/spatie/fork/Check%20\u0026%20fix%20styling?label=code%20style)](https://github.com/spatie/fork/actions?query=workflow%3A\"Check+%26+fix+styling\"+branch%3Amaster)\n[![Total Downloads](https://img.shields.io/packagist/dt/spatie/fork.svg?style=flat-square)](https://packagist.org/packages/spatie/fork)\n\nThis package makes it easy to run PHP concurrently. Behind the scenes, concurrency is achieved by forking the main PHP process to one or more child tasks.\n\nIn this example, where we are going to call an imaginary slow API, all three closures will run at the same time.\n\n```php\nuse Spatie\\Fork\\Fork;\n\n$results = Fork::new()\n    -\u003erun(\n        fn () =\u003e (new Api)-\u003efetchData(userId: 1),\n        fn () =\u003e (new Api)-\u003efetchData(userId: 2),\n        fn () =\u003e (new Api)-\u003efetchData(userId: 3),\n    );\n\n$results[0]; // fetched data of user 1\n$results[1]; // fetched data of user 2\n$results[2]; // fetched data of user 3\n```\n## How it works under the hood\n\n✨ In this [video on YouTube](https://www.youtube.com/watch?v=IJXzc46MFPM), we explain how the package works internally.\n\n## Support us\n\n[\u003cimg src=\"https://github-ads.s3.eu-central-1.amazonaws.com/fork.jpg?t=1\" width=\"419px\" /\u003e](https://spatie.be/github-ad-click/fork)\n\nWe invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can\nsupport us by [buying one of our paid products](https://spatie.be/open-source/support-us).\n\nWe highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.\nYou'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards\non [our virtual postcard wall](https://spatie.be/open-source/postcards).\n\n## Requirements\n\nThis package requires PHP 8 and the [pcntl](https://www.php.net/manual/en/intro.pcntl.php) extensions which is installed in many Unix and Mac systems by default.\n\n❗️ [pcntl](https://www.php.net/manual/en/intro.pcntl.php) only works in CLI processes, not in a web context.\n❗️ [posix](https://www.php.net/manual/en/book.posix.php) required for correct handling of process termination for Alpine Linux.\n\n## Installation\n\nYou can install the package via composer:\n\n```bash\ncomposer require spatie/fork\n```\n\n## Usage\n\nYou can pass as many closures as you want to `run`. They will be run concurrently. The `run` function will return an array with the return values of the executed closures.\n\n```php\nuse Spatie\\Fork\\Fork;\n\n$results = Fork::new()\n    -\u003erun(\n        function ()  {\n            sleep(1);\n\n            return 'result from task 1';\n        },\n        function ()  {\n            sleep(1);\n\n            return 'result from task 2';\n        },\n        function ()  {\n            sleep(1);\n\n            return 'result from task 3';\n        },\n    );\n\n// this code will be reached this point after 1 second\n$results[0]; // contains 'result from task 1'\n$results[1]; // contains 'result from task 2'\n$results[2]; // contains 'result from task 3'\n```\n\n### Running code before and after each closure\n\nIf you need to execute some code before or after each callable passed to `run`, you can pass a callable to `before` or `after` methods. This callable passed will be executed in the child process right before or after the execution of the callable passed to `run`.\n\n### Using `before` and `after` in the child task\n\nHere's an example where we are going to get a value from the database using a Laravel Eloquent model. In order to let the child task use the DB, it is necessary to reconnect to the DB. The closure passed to `before` will run in both child tasks that are created for the closures passed to `run`.\n\n```php\nuse App\\Models\\User;\nuse Illuminate\\Support\\Facades\\DB;\nuse Spatie\\Fork\\Fork;\n\n Fork::new()\n    -\u003ebefore(fn () =\u003e DB::connection('mysql')-\u003ereconnect())\n    -\u003erun(\n        fn () =\u003e User::find(1)-\u003esomeLongRunningFunction(),\n        fn () =\u003e User::find(2)-\u003esomeLongRunningFunction(),\n    );\n```\n\nIf you need to perform some cleanup in the child task after the callable has run, you can use the `after` method on a `Spatie\\Fork\\Fork` instance.\n\n### Using `before` and `after` in the parent task.\n\nIf you need to let the callable passed to `before` or `after` run in the parent task, then you need to pass that callable to the `parent` argument.\n\n```php\nuse App\\Models\\User;\nuse Illuminate\\Support\\Facades\\DB;\nuse Spatie\\Fork\\Fork;\n\n Fork::new()\n    -\u003ebefore(\n        parent: fn() =\u003e echo 'this runs in the parent task'\n    )\n    -\u003erun(\n        fn () =\u003e User::find(1)-\u003esomeLongRunningFunction(),\n        fn () =\u003e User::find(2)-\u003esomeLongRunningFunction(),\n    );\n```\n\nYou can also pass different closures, to be run in the child and the parent task\n\n```php\nuse Spatie\\Fork\\Fork;\n\nFork::new()\n    -\u003ebefore(\n        child: fn() =\u003e echo 'this runs in the child task',\n        parent: fn() =\u003e echo 'this runs in the parent task',\n    )\n    -\u003erun(\n        fn () =\u003e User::find(1)-\u003esomeLongRunningFunction(),\n        fn () =\u003e User::find(2)-\u003esomeLongRunningFunction(),\n    );\n```\n\n### Returning data\n\nAll output data is gathered in an array and available as soon as all children are done. In this example, `$results` will contain three items:\n\n```php\n$results = Fork::new()\n    -\u003erun(\n        fn () =\u003e (new Api)-\u003efetchData(userId: 1),\n        fn () =\u003e (new Api)-\u003efetchData(userId: 2),\n        fn () =\u003e (new Api)-\u003efetchData(userId: 3),\n    );\n```\n\nThe output is also available in the `after` callbacks, which are called whenever a child is done and not at the very end:\n\n```php\n$results = Fork::new()\n    -\u003eafter(\n        child: fn (int $i) =\u003e echo $i, // 1, 2 and 3\n        parent: fn (int $i) =\u003e echo $i, // 1, 2 and 3\n    )\n    -\u003erun(\n        fn () =\u003e 1,\n        fn () =\u003e 2,\n        fn () =\u003e 3,\n    );\n```\n\nFinally, return values from child tasks are serialized using PHP's built-in `serialize` method. This means that you can return anything you can normally serialize in PHP, including objects:\n\n```php\n$result = Fork::new()\n    -\u003erun(\n        fn () =\u003e new DateTime('2021-01-01'),\n        fn () =\u003e new DateTime('2021-01-02'),\n    );\n```\n\n### Configuring concurrency\n\nBy default, all callables will be run in parallel. You can however configure a maximum amount of concurrent processes:\n\n```php\n$results = Fork::new()\n    -\u003econcurrent(2)\n    -\u003erun(\n        fn () =\u003e 1,\n        fn () =\u003e 2,\n        fn () =\u003e 3,\n    );\n```\n\nIn this case, the first two functions will be run immediately and as soon as one of them finishes, the last one will start as well.\n\n## Testing\n\n```bash\ncomposer test\n```\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.\n\n## Contributing\n\nPlease see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.\n\n## Security Vulnerabilities\n\nPlease review [our security policy](../../security/policy) on how to report security vulnerabilities.\n\n## Credits\n\n- [Brent Roose](https://github.com/brendt)\n- [Freek Van der Herten](https://github.com/freekmurze)\n- [All Contributors](../../contributors)\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","funding_links":["https://github.com/sponsors/spatie"],"categories":["PHP"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Ffork","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspatie%2Ffork","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Ffork/lists"}