kachkaev/php-r-bundle
A Symfony bundle that brings R statistical computing into PHP applications, enabling you to run R scripts, pass data between PHP and R, and incorporate R-powered analysis into Symfony projects.
which R
R --version
sudo -u www-data R --version
composer require kachkaev/php-r-bundle
It depends on kachkaev/php-r, which provides the actual RClient.app/AppKernel.php:
new Kachkaev\PHPRBundle\KachkaevPHPRBundle(),
app/config/config.yml:
kachkaev_php_r:
r_binary: /usr/bin/R
Check the bundle's DependencyInjection/Configuration.php and Resources/config/services.yml for the exact config keys and service ID — the bundle exposes the client as a service (commonly aliased to kachkaev_php_r or the RClient class).Resources/config/services.yml to confirm the service ID and whether it is public. Then inject it:
use Kachkaev\PHPR\RClient;
class ReportController
{
public function summaryAction()
{
/** @var RClient $r */
$r = $this->get('kachkaev_php_r'); // or type-hint RClient if autowiring is enabled
$result = $r->run('mean(c(1, 2, 3, 4))');
return new Response($result->getOutput());
}
}
$r->run('values <- c(10, 20, 30, 40)');
$r->run('avg <- mean(values)');
echo $r->run('avg')->getOutput();
[1] prefixes and formatting noise. Prefer jsonlite in R and json_decode in PHP, or write/read a temp CSV:
$script = <<<'R'
library(jsonlite)
toJSON(list(mean = mean(values), sd = sd(values)), auto_unbox = TRUE)
R;
$data = json_decode($r->run($script)->getOutput(), true);
read.csv()/readRDS() inside R, or carefully quote/escape values before assigning R variables.RClient out of controllers; create e.g. AppBundle\Analytics\RStatsService that owns script generation, error handling, and result parsing. This makes testing and later replacement much easier.png('/tmp/chart.png'), build the plot, dev.off(), then serve/attach the file from PHP.run() call. Log the generated script and R output so failures are reproducible.proc_open/process execution. Many hosts disable proc_open, restrict open_basedir, or run PHP-FPM as a user without access to /usr/bin/R. Test the exact runtime user, not your shell user.system(), read files, and execute shell commands. Never concatenate raw request data into a script. Whitelist operations and pass parameters through files or strictly escaped variables.getOutput() returns R's printed representation, not typed PHP data. Normalize whitespace and [1] prefixes, and prefer JSON for anything non-trivial./usr/bin/R; Windows uses Rscript.exe. Make the binary path environment-specific config, not hard-coded.Rscript script.R, and compare stderr/exit codes. Most failures are missing R packages, wrong working directory, or permissions.symfony/process wrapper (run Rscript --vanilla script.R) is usually straightforward and removes a dead dependency.How can I help you explore Laravel packages today?