Eliminate Spaghetti Code Using PHP Rules

Eliminate Spaghetti Code Using PHP Rules

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:

  1. Download the rules.zip archive.
  2. Unzip the archive in the htdocs directory.
  3. Configure the database from the htdocs/rules/system/application/config path according to your local parameters.
  4. Set the hostname, username, password, etc.
  5. Create a new database named “rules” in MySQL.
  6. Run the index.php script from the rules/index.php path.
  7. To install the two examples select the “install wizard” link (see Figure 1).
  8.  
    Figure 1. Installing PHP Rules: Install PHP Rules by clicking on the install wizard link.

  9. Finally, click the Install the Demo Database button (see Figure 2).
  10.  
    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.

 
Figure 5. Rules Database: The figure shows the tables and structure of the rules database.

 
Figure 6. Average Table: The average table contains a student ID and that student’s academic average value.

 
Figure 7. Student Table: The student table contains a list of variables and their values for each student.

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.

devx-admin

devx-admin

Share the Post:
Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India,

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1