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

Add loop mode (`-L`) in the CLI SAPI #2

Open
wants to merge 7 commits into
base: PHP-7.2
from

Conversation

Projects
None yet
1 participant
@mnapoli
Copy link
Owner

mnapoli commented Dec 7, 2018

This is a pull request that I opened in my own fork to preview the diff and allow code review.

This PR adds a new "Loop" mode that can be used with -L. For example: php -L script.php.

This mode runs the script in a loop.

The big difference with doing a while(true) {} loop in PHP is that every execution of the script is isolated from the other executions.

Use cases

  • Workers, i.e. processing jobs in a message queue: instead of running in a loop the script can process one job, the "Loop" mode will ensure the script will loop => each job will be processed in a fresh PHP environment, meaning no memory leaks, no shared state, etc.
  • AWS Lambda: by running php -L each event/request would be processed in an isolated PHP environment without having the overhead of starting a new process: see mnapoli/bref-bootstrap-benchmarks#14

Example

Before:

<?php
// script.php
$a = 'foo';
while (true) {
    echo $a . PHP_EOL;
    $a = 'bar';
}
$ php -L script.php
foo
bar
bar
[...]

With the "loop mode":

<?php
// script.php
$a = 'foo';
echo $a . PHP_EOL;
$a = 'bar';
$ php -L script.php
foo
foo
foo
[...]

Understanding how it works

This is pseudo code of the new -L mode:

	while (is_running) {
        // Boot the PHP engine
		php_request_startup();

        // Execute `index.php` in the current process
        php_run_script("index.php");

        // Reset the PHP engine (clear variables, memory, open resources, etc.)
        php_request_shutdown();
	}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.