HP Rules is a rule engine that lets you separate conditional logical statement from your source code and from the database, placing the conditional logic in reusable files, where you can define and manage them independently.
This article demonstrates how to:
- Install PHP Rules and execute rules stored in text files or a database
- Create your own rules, starting from a particular case
- Evaluate a rule stored in a text file
- Evaluate a rule stored in a database
Download and Install PHP Rules
You can download PHP Rules here. At the bottom of that page, you’ll see a section titled “Download and install PHP Rules.” To install PHP Rules follow these steps:
- Download the rules.zip archive.
- Unzip the archive in the htdocs directory.
- Configure the database from the htdocs/rules/system/application/config path according to your local parameters.
- Set the hostname, username, password, etc.
- Create a new database named “rules” in MySQL.
- Run the index.php script from the rules/index.php path.
- To install the two examples select the “install wizard” link (see Figure 1).
- Finally, click the Install the Demo Database button (see Figure 2).
![]() | |
Figure 1. Installing PHP Rules: Install PHP Rules by clicking on the install wizard link. |
![]() | |
Figure 2. Install the Demo Database: You need the demonstration database to run the examples. |
![]() | |
Figure 3. Running the Examples: Click on each link to run the two examples. |
On the http://localhost/rules/index.php/rules/install/db page you’ll find links to the two examples as shown in Figure 3.
Using PHP Rules
As the two examples illustrate, you must first create Rule and RuleContext files to get the resulting proposition. The Rule file contains simple statements of facts written using propositions, operators, and variables, while the RuleContext file contains data you want to test against the rule, stored either as plain text or in a database. The Rule file evaluates the RuleContext file and returns a Boolean value that represents whether the information in the RuleContext conforms to the Rule.
In this article, the Rules files correspond to the examples. You can download all the sample code for this article. The two text files SuitableForScholarship.rul and SuitableForScholarship.txt.con, and the relational database file SuitableForScholarship.sql.con are stored in the rules/data directory. The rule examples determine whether a student is suitable for a scholarship, testing against RuleContext data stored in both text files and the database. The rules that a student must meet to get a scholarship are:
- The student should have an annual grade point average equal to 9.5.
- OR the student should have participated in a national contest AND won first prize.
- The student should be in high school.
- The parents must agree that the student should apply for the scholarship.
The Rule file that structures the rules described above is SuitableForScholarShip.rul:
# SuitableForScholarShip.rul# Rule establishing when a student can# gets an international scholarshipstudentAnnualAverage EQUALS 9.5studentIsParticipatingToContest IS true studentIsGettingFirstPrize IS trueANDORstudentIsInHighschool IS truestudentParentsAreAgree IS trueANDAND
Author’s Note: Rules are case sensitive; miscapitalizing rule keywords or phrases such as “is TRUE” or “Is True” or “equals” will raise an error. |
Notice that the SuitableForScholarShip.rul file is a plain text file with a .rul extension. The rules themselves are written using Reverse Polish Notation (RPN). You can find more about RPN here.
“Translating” these rules from the bottom up you get something like this:
(studentParentsAreAgree AND studentIsInHighschool) AND ((studentIsGettingFirstPrize AND studentIsParticipatingToContest) OR studentAnnualAverage))
Author’s Note: Both the examples in this article use the SuitableForScholarShip.rul file, but with different RuleContext files. |
Create a RuleContext Text File
To generate a Boolean resulting proposition, you need both a Rule file—in this case the SuitableForScholarShip.rul file, described earlier—and an explicit case, represented by the RuleContext file. For this first example, the RuleContext file is SuitableForScholarShip.txt.con, listed below:
# SuitableForScholarShip.txt.con:studentAnnualAverage EQUALS 8.0studentIsParticipatingToContest IS truestudentIsGettingFirstPrize IS truestudentIsInHighschool IS truestudentParentsAreAgree IS true
As you can see, this RuleContext test contains the data for a specific situation. This student’s annual average is 8.0; he participated in a national contest and received the first prize; the student is in high school, and the student’s parents agree with this scholarship application. Using these facts according to the logic in the Rule file, this student should receive the scholarship: in other words, the resulting proposition value should be TRUE.
Notice that the RuleContext data for the two examples (one that loads and execute the rules from Rule and RuleContext text files, and the other from a database) are completely different. Another document that differs is the .php script. In the PHP Rules examples the custodian.php (/htdocs/rules/system/application/controllers/rules) script contains the loadTxt and loadSql functions; which one gets called depends on the mode. The text file example uses the file http://localhost/rules/index.php/rules/custodian/loadtxt/4; the database example uses http://localhost/rules/index.php/rules/custodian/loadsql/4. The Student.php script shown below calls the loadTxt function:
load->model('rule/RuleLoader', 'loader'); // FCPATH is defined in the /index.php file. $this->appPhysicalPath = str_replace( 'index.php', '', str_replace( '\', '/', FCPATH ) ); // See whether we can do the same thing with this helper: // $this->load->helper('file'); } public function loadTxt($id) { $this->load->model( 'rule/strategy/TxtFileLoaderStrategy', 'strategy' ); $this->loader->setStrategy($this->strategy); $data['rule']= $this->loader->loadRule( $this->appPhysicalPath . 'data/SuitableForScholarship.rul'); $data['ruleContext'] = $this->loader->loadRuleContext( $this-> appPhysicalPath . 'data/SuitableForScholarship.txt.con', $id ); $data['result'] = $data['rule']-> evaluate($data['ruleContext']); $data['ruleText'] = read_file( 'data/SuitableForScholarship.rul'); $data['ruleContextText'] = read_file( 'data/SuitableForScholarship.txt.con'); $this->load->view('studentview', $data); }}?>
To modify the implicit rules description, save the student.php script in the same directory as the custodian.php script (/htdocs/rules/system/application/controllers/rules).
Again, to determine eligibility, you have to compare each specific student’s data with the rule set. Simply modify the ruleview.php page (htdocs/rules/system/application/views) with your own view page (in this example, studentview.php) and save it in the same directory.
To see the expected result, browse to the local URL http://localhost/rules/index.php/rules/student/loadtxt/4. The result should look like Figure 4.
![]() | |
Figure 4. Evaluating Rules: Here’s the sample output from evaluating rule data stored in a text file. |
Create and Evaluate a Rule from a Database
To create a RuleContext file for this case (we established above that we will use the same Rule file, SuitableForScholarShip.rul, listed in the above section), first we should do is to create two tables in the MySQL database, rules, created at installation of the PHP Rules. Figure 5 shows the tables used in this section: average and student, while Figure 6 and Figure 7 show the columns defined for the two tables.
|
|
|
After creating the rules database and its structure, it’s time to create the RuleContext file. The format of this file is slightly more complex than the previous example:
Rule_Element_Type|Rule_Element_Name| SQL_Statement|Expected_Return_Data_Type_from_SQL_Query
The Rule file for the database example is identical to the text file example, but the RuleContext is different; in this case:
- The student’s annual average is 9.5.
- The student participated in a national contest, but didn’t get first prize.
- The student is in high school.
- The student’s parents have agreed that the student should apply for the scholarship.
In this case, according to the Rule file (SuitableForScholarShip.rul) the student should not receive a scholarship; in other words, the resulting proposition should have value=FALSE.
With the rules clearly established and the table structures shown in Figure 6 and Figure 7, the SQL statements are very intuitive. The RuleContext file for this case looks like this:
# Format of this file is:# Rule_Element_Type|Rule_Element_Name| SQL_Statement| Expected_Return_Data_Type_from_SQL_Querya|studentAnnualAverage| SELECT a.average FROM rules.average a WHERE a.variable_name = 'studentAnualAverage';|doubles|studentIsParticipatingToContest| SELECT if(((SELECT s.variable_name FROM rules.student s WHERE s.id = ? ) = 1), 1, 0);|booleans|studentIsGettingFirstPrize| SELECT if((( SELECT s.variable_name FROM rules.student s WHERE s.id = ? ) = 1), 1, 0);|booleans|studentIsInHighschool| SELECT if((( SELECT s.variable_name FROM rules.student s WHERE s.id = ? ) = 1), 1, 0);|booleans|studentParentsAreAgree| SELECT if((( SELECT s.variable_name FROM rules.student s WHERE s.id = ? ) = 1), 1, 0);|boolean
Here’s the student.php script that calls the loadSql function with the appropriate arguments:
load->model( 'rule/RuleLoader', 'loader' ); // FCPATH is defined in the /index.php file. $this->appPhysicalPath = str_replace( 'index.php', '', str_replace( '\', '/',FCPATH ) ); // See whether we can do the same thing with this helper: // $this->load->helper( 'file' ); } public function loadSql( $id ) { $this->load->model( 'rule/strategy/SqlFileLoaderStrategy', 'strategy' ); $this->loader->setStrategy( $this->strategy ); $data[ 'rule' ]= $this->loader->loadRule( $this->appPhysicalPath . 'data/SuitableForScholarShip.rul' ); $data[ 'ruleContext' ] = $this->loader->loadRuleContext( $this-> appPhysicalPath . 'data/SuitableForScholarShip.sql.con', $id ); $data[ 'result' ] = $data[ 'rule' ]-> evaluate( $data[ 'ruleContext' ] ); $data[ 'ruleText' ] = read_file( 'data/SuitableForScholarShip.rul' ); $data[ 'ruleContextText' ] = read_file( 'data/SuitableForScholarShip.sql.con' ); $this->load->view( 'ruleview', $data ); } }?>
To see the expected result, browse to the URL http://localhost/rules/index.php/rules/student/loadsql/1. The result should look like Figure 8.
![]() | |
Figure 8. Evaluate a RuleContext from a Database: Here’s the output of evaluating a rule against data stored in the rules database. |
At this point, you’ve seen how to install PHP Rules and how to execute RuleContext data stored in both text files and a database. You’ve also seen how to create your own rules and how to call them from a PHP program. PHP Rules is well-suited for situations where you have a large number of test cases that you need to test against a set of rules that may change. By separating the rules and the data from your program code, you can evaluate rules even when you don’t know in advance exactly what those rules are going to be.