Specify dependencies in PHP
You use Composer to manage dependencies in PHP.
Installing Composer
If you don't already have Composer installed, you can do so as follows:
Download Composer to any location you desire.
Once it is downloaded, move the
composer.pharfile to a directory that is in your system path, for example:mv composer.phar /usr/local/bin/composer
Creating a composer.json file
The composer.json file lists your function's dependencies. You can either
create it by hand, or you can run the following command:
composer init
When you run this command, it interactively asks you to fill in the fields, while offering some smart defaults.
Declaring dependencies
To declare dependencies, add a composer.json file containing dependencies to your
function code directory. In this example, we require the
Functions Framework
and add a start script:
{ "require": { "php": ">= 8.1", "google/cloud-functions-framework": "^1.1" }, "scripts": { "start": [ "Composer\\Config::disableProcessTimeout", "FUNCTION_TARGET=helloHttp php -S localhost:${PORT:-8080} vendor/google/cloud-functions-framework/router.php" ] } }
Note that scripts defined in your
composer.json file
will not run when Composer can use a cached result.
Add Functions Framework as a dependency
The Cloud Run functions PHP runtime requires the Functions Framework to be an
explicit dependency. To add Functions Framework as a dependency, run the
following command in the directory containing your function code (this directory
must also contain the composer.json file):
composer require google/cloud-functions-framework
This adds the Functions Framework to your composer.json and installs the
package in the vendor/ directory.
autoload.php file
One of the files contained in your vendor/ directory is autoload.php.
Add the following line to the top of your PHP scripts to require the
autoload.php file, which automatically requires your function's other
dependencies:
require_once __DIR__ . '/vendor/autoload.php';
By default, the vendor/ directory is ignored in the generated
.gcloudignore file to reduce the
number of files sent in deployment.
Updating dependencies
To update your function's dependencies and the composer.lock file, use the
update command:
composer update
This resolves all dependencies of the project and writes their exact versions into
composer.lock.