Using namespaces in games projects
Posted: 10 October 2024, 08:58
You can now write your game class in a new way, using namespces and taking benefit of PSR-4!
From now on, the new project will generate a Game.php file in modules/php, with a namespaced class, and will be able to load your other classes in this directory using PSR-4 (without needing to manually write `require_once`).
The new Game.php files looks like this:
To take advantage of the autoload for your other classes, just follow PSR-4. For those not familiar with it, I've added some examples here : https://en.doc.boardgamearena.com/Main_ ... er_classes
BGA will try to load a `Bga\Games\YourGameName\Game` class in `modules/php/Game.php`.
If it isn't found, it will fallback to the "legacy way" of loading `YourGameName` class in `yourgamename.game.php`, so your already started projects and older games still work (but PSR-4 autoload won't be activated in this case).
For your new projects, please use it (especially if you copy one project to the other instead of starting from the blank template for each new project).
(If you convert a "legacy" project to the new way, you will need to add `\` before exception classes so `BgaUserException` becomes `\BgaUserException`)
The Reversi project & tutorial has been updated in that way, so you can use it as an example
From now on, the new project will generate a Game.php file in modules/php, with a namespaced class, and will be able to load your other classes in this directory using PSR-4 (without needing to manually write `require_once`).
The new Game.php files looks like this:
Code: Select all
declare(strict_types=1);
namespace Bga\Games\YourGameName;
require_once( APP_GAMEMODULE_PATH.'module/table/table.game.php' );
class Game extends \Table {
...
BGA will try to load a `Bga\Games\YourGameName\Game` class in `modules/php/Game.php`.
If it isn't found, it will fallback to the "legacy way" of loading `YourGameName` class in `yourgamename.game.php`, so your already started projects and older games still work (but PSR-4 autoload won't be activated in this case).
For your new projects, please use it (especially if you copy one project to the other instead of starting from the blank template for each new project).
(If you convert a "legacy" project to the new way, you will need to add `\` before exception classes so `BgaUserException` becomes `\BgaUserException`)
The Reversi project & tutorial has been updated in that way, so you can use it as an example