This is a documentation for Board Game Arena: play board games online !
User:SwHawk/Create Modular Code
This page will cover steps you can take as a BGA developer to make your code more modular and better organized. The way the framework is implemented makes the game logic and the interface logic files very monolithic. While this is not a problem in itself, even simple to moderately complex game may require this files to be over 5k lines of code. Thus you can quickly become lost in all the functions you need to declare, where they are declared, and where they are called.
But there are steps that you can follow to take advantage of PHP's Object Oriented Code and the dojo toolkit's AMD loader to organize your code in separate files. Let's see what's available:
On the PHP side
include
vs require
Throughout this section, I'll make heavy use of PHP's require_once
control structure. Why am I using require(_once)
instead of include_once
? Because if an error exists in a PHP file that you try to include
, only a warning will be thrown, but the script will continue in spite of the error. Using require
if the included file has an error, the script dies when the inclusion takes places, throwing a fatal error (E_COMPILE_ERROR).
That way, I'm sure the classes, traits or interfaces I'm including are syntax error free.
Game logic methods
The way the framework is implemented, your game logic is gathered inside a class (`YourProjectName`) extending the `Table` class. You define your methods there so that they may be called from other parts of the framework (as long as they're public methods obviously).
But you can take advantage of PHP Traits. In a nutshell, Traits are a collection of methods that can be reused in different classes, to avoid code duplication. Here we're not going to reuse them anywhere else than in the game class, but this little trick allows us to put methods definitions in other files, and in so doing to avoid monolithic code.
Basically you create a Trait in th /modules/
directory, for instance:
[[modules/UtiltityFunctionsTrait.php]] <?php namespace YourProjectNamespace\Modules; trait UtilityFunctionsTrait { public function myFirstUtilityFunction($args) { //Your code here } }
Then you can include it in you project's `game.php` file like so:
[[X_game.php]] <?php /** *------ * BGA framework: © Gregory Isabelli <gisabelli@boardgamearena.com> & Emmanuel Colin <ecolin@boardgamearena.com> * ProgressEvolutionTechnologySwH implementation : © <Your name here> <Your email address here> * * This code has been produced on the BGA studio platform for use on http://boardgamearena.com. * See http://en.boardgamearena.com/#!doc/Studio for more information. * ----- * * progressevolutiontechnologyswh.game.php * * This is the main file for your game logic. * * In this PHP file, you are going to defines the rules of the game. * */ require_once 'modules/UtilityFunctionsTrait.php'; //Here we require the trait to be loaded when the class is loaded use YourProjectNamespace\Modules\UtilityFunctionsTrait; //We import the trait to be used directly as UtilityFunctionsTraits, otherwise we would have to use the Fully qualified class name (YourProjectNamespace\Modules\UtilityFunctionsTrait) class YourProjectName extends Table { //... ////////////////////////////////////////////////////////////////////////////// //////////// Utility functions //////////// /* In this space, you can put any utility methods useful for your game logic */ use UtilityFunctionsTrait; //Here we actually include the trait inside the class, making all the trait's methods available as class methods, keeping their visibility scope (so a private method is still private) }
Support classes
Basically, the same as traits, you put your classes definitions into files that live under the /modules/
directory (don't forget to namespace your classes), and then require them at the top of X_game.php
, and voilà, you're done
Adding autoloader support
Coding standards
Even for simple games, you might end up having a dozen of traits and support classes. You can require them all in your X_game.php
. Or you can use an autoloader, which will load the necessary classes and traits at runtime. There are two PSRs dealing with autloading standards (namely PSR-0 which is marked as deprecated and PSR-4) which state that your namespaces should be a reflection of the directory structure of your project.
Basically, when creating namespaces, you choose a namespace prefix. For example, you could use your BGA handle and the project name as a namespace prefix (would result in \SwHawk\X
in my case), and then the rest of the namespace would be the directory the file is in. I usually group classes and traits by the function they have in my project, so my /modules/
directory looks like that:
modules/ php/ Factory/ //Holds my factory classes AFactoryClass.php //The namespace for this file would be \SwHawk\X\Factory, and the fully qualified class name would be \SwHawk\X\Factory\AFactoryClass ... Object/ //Holds my support classes ObjectA.php //The namespace for this file would be \SwHawk\X\Object, and the fully qualified class name would be \SwHawk\X\Object\ObjectA ... Traits/ //Holds my traits UtilityFunctionsTrait.php //The namespace for this file would be \SwHawk\X\Traits, and the fully qualified class name would be \SwHawk\X\Traits\UtilityFunctionsTrait ... ... ...
Autoloader function for development
While your project is under development, you usually create, move and remove classes as part of the development process. So you usually need an autoloading function that can handle a lot of flexibility. Basically once you import a class using the use
, the autoloading function will determine which file to require
using its fully qualified class name, and then require
. Such a function would have the following code (borrowed and adapted from [1]):
spl_autoload_register(function ($class) { // project-specific namespace prefix, adapt to your needs $prefix = 'SwHawk\\X\\'; // base directory for the namespace prefix, this file would usually reside in the modules/php/includes/ directory, so the base directory for all my classes would be a level higher $base_dir = __DIR__ . '/../'; // does the class use the namespace prefix? $len = strlen($prefix); if (strncmp($prefix, $class, $len) !== 0) { // no, move to the next registered autoloader return; } // get the relative class name $relative_class = substr($class, $len); // replace the namespace prefix with the base directory, replace namespace // separators with directory separators in the relative class name, append // with .php $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php'; // if the file exists, require it if (file_exists($file)) { require $file; } });
Autoloader function for production
Once you're moving your game to production, the autoloader function provided before isn't optimized. Once in production, the directory tree should not be modified, so you can change the earlier autoloader to a classmap based one. Basically, you build an associative array with the fully qualified classes names as keys and the filepath as the value. An example would look like so:
spl_autoload_register(function ($class) { static $classmap = array( "SwHawk\\X\\Factory\\AFactoryClass" => __DIR__ . "/../Factory/AFactoryClass.php", ... ); if(array_key_exists($class)) { require $classmap[$class]; } else { return; } }
This autoloader is better suited to production since it won't use expensive calls like file_exists($filename)
.