Creating Your First Rule
Now that you have MilliRules installed and initialized, let's create your first rule. This hands-on tutorial will walk you through building a simple but functional rule that logs admin dashboard access in WordPress.
Anatomy of a Rule#Copied!
Every MilliRules rule consists of three main parts:
- Rule Creation - Define the rule with an ID and type
- Conditions (when) - Specify when the rule should execute
- Actions (then) - Define what happens when conditions are met
Here's the basic structure:
1use MilliRulesRules;
2
3Rules::create('rule_id')
4 ->when()
5 // Add conditions here
6 ->then()
7 // Add actions here
8 ->register();
Your First Rule: Log Admin Access#Copied!
Let's create a rule that logs a message whenever someone accesses the WordPress admin dashboard.
Step 1: Initialize MilliRules#Copied!
Add this to your plugin's main file or functions.php:
1use MilliRulesMilliRules;
2use MilliRulesRules;
3
4// Initialize the rule engine
5MilliRules::init();
Step 2: Create Your First Rule#Copied!
1use MilliRulesRules;
2
3// Create a rule that runs on WordPress 'init' hook
4Rules::create('log_admin_access', 'wp')
5 ->title('Log Admin Dashboard Access') // Optional
6 ->order(10) // Optional
7 ->when()
8 ->request_url('/wp-admin/*') // Matches any admin URL
9 ->is_user_logged_in() // User must be logged in
10 ->then()
11 ->custom('log_message', ['value' => 'Admin dashboard accessed'])
12 ->register();
Step 3: Register the Custom Action#Copied!
Since log_message is a custom action, let's register it:
1use MilliRulesRules;
2use MilliRulesContext;
3
4Rules::register_action('log_message', function($args, Context $context) {
5 $message = $args['message'] ?? $args[0] ?? 'No message';
6 error_log('MilliRules: ' . $message);
7});
Complete Example#Copied!
Here's everything together in a WordPress plugin context:
1/**
2 * Plugin Name: My First MilliRules Plugin
3 * Description: Logs admin dashboard access using MilliRules
4 * Version: 1.0.0
5 */
6
7require_once __DIR__ . '/vendor/autoload.php';
8
9use MilliRulesMilliRules;
10use MilliRulesRules;
11use MilliRulesContext;
12
13// Initialize MilliRules
14MilliRules::init();
15
16// Register custom log action
17Rules::register_action('log_message', function($args, Context $context) {
18 $message = $args['message'] ?? $args[0] ?? 'No message';
19 error_log('MilliRules: ' . $message);
20});
21
22// Create the rule
23Rules::create('log_admin_access', 'wp')
24 ->title('Log Admin Dashboard Access')
25 ->order(10)
26 ->when()
27 ->request_url('/wp-admin/*')
28 ->is_user_logged_in()
29 ->then()
30 ->custom('log_message', ['value' => 'Admin dashboard accessed'])
31 ->register();
wp-content/debug.log if WP_DEBUG_LOG is enabled) to see the logged messages when you access the WordPress admin dashboard.Understanding What Just Happened#Copied!
Let's break down what this rule does:
-
Rule Creation:
Rules::create('log_admin_access', 'wp')creates a new rule with IDlog_admin_accessand typewp(WordPress) -
Metadata:
->title()and->order()add descriptive information and control execution sequence -
Conditions: The
->when()builder defines conditions that must be met:- Request URL matches
/wp-admin/*(wildcard pattern) - User is logged in
- Request URL matches
-
Actions: The
->then()builder defines what happens when conditions match:- Log a message via the custom
log_messageaction
- Log a message via the custom
-
Registration:
->register()registers the rule with MilliRules
Simple Condition Examples#Copied!
Here are some common conditions you can use:
URL Matching#Copied!
1// Exact match
2->when()->request_url('/contact')
3
4// Wildcard pattern
5->when()->request_url('/blog/*')
6
7// Multiple URLs (OR logic)
8->when_any()
9 ->request_url('/about')
10 ->request_url('/contact')
HTTP Method Checking#Copied!
1// Check for POST requests
2->when()->request_method('POST')
3
4// Check for GET or HEAD (using array)
5->when()->request_method(['GET', 'HEAD'])
User Status (WordPress)#Copied!
1// User must be logged in
2->when()->is_user_logged_in()
3
4// User must NOT be logged in
5->when()->is_user_logged_in(false)
Cookie Checking#Copied!
1// Check if cookie exists
2->when()->cookie('session_id')
3
4// Check cookie value
5->when()->cookie('user_preference', 'dark_mode')
Simple Action Examples#Copied!
Logging#Copied!
1// Register a logging action
2Rules::register_action('log', function($args, Context $context) {
3 error_log('MilliRules: ' . ($args['value'] ?? ''));
4});
5
6// Use it in a rule
7->then()->custom('log', ['value' => 'Something happened'])
Redirects#Copied!
1// Register a redirect action
2Rules::register_action('redirect', function($args, Context $context) {
3 $url = $args['url'] ?? '/';
4 wp_redirect($url);
5 exit;
6});
7
8// Use it in a rule
9->then()->custom('redirect', ['url' => '/login'])
Setting Headers#Copied!
1// Register a cache header action
2Rules::register_action('set_cache', function($args, Context $context) {
3 $duration = $args['duration'] ?? 3600;
4 header('Cache-Control: max-age=' . $duration);
5});
6
7// Use it in a rule
8->then()->custom('set_cache', ['duration' => 7200])
Running Rules#Copied!
By default, WordPress rules execute automatically on their specified hook. You don't need to manually trigger execution.
However, you can also execute rules manually:
1use MilliRulesMilliRules;
2
3// Execute all registered rules
4$result = MilliRules::execute_rules();
5
6// Check execution statistics
7echo 'Rules processed: ' . $result['rules_processed'] . "n";
8echo 'Rules matched: ' . $result['rules_matched'] . "n";
9echo 'Actions executed: ' . $result['actions_executed'] . "n";
->on('hook_name') execute automatically when that hook fires. You only need manual execution for PHP-only rules or when testing.Common Beginner Mistakes#Copied!
1. Forgetting to Call register()#Copied!
1// ❌ Wrong - rule never registered
2Rules::create('my_rule')
3 ->when()->request_url('/test')
4 ->then()->custom('action');
5// Missing ->register()
6
7// ✅ Correct
8Rules::create('my_rule')
9 ->when()->request_url('/test')
10 ->then()->custom('action')
11 ->register();
2. Using Undefined Custom Actions#Copied!
1// ❌ Wrong - 'send_email' not registered
2Rules::create('notify')
3 ->when()->request_url('/contact')
4 ->then()->custom('send_email') // Not defined!
5 ->register();
6
7// ✅ Correct - register action first
8Rules::register_action('send_email', function($args, Context $context) {
9 // Email sending logic here
10});
11
12Rules::create('notify')
13 ->when()->request_url('/contact')
14 ->then()->custom('send_email')
15 ->register();
3. Incorrect Condition Logic#Copied!
1// ❌ Wrong - using when() with single condition that should be OR
2Rules::create('public_access')
3 ->when() // This uses AND logic by default
4 ->request_url('/public')
5 ->request_url('/open') // Can't match both!
6 ->then()->custom('grant_access')
7 ->register();
8
9// ✅ Correct - use when_any() for OR logic
10Rules::create('public_access')
11 ->when_any() // Use OR logic
12 ->request_url('/public')
13 ->request_url('/open')
14 ->then()->custom('grant_access')
15 ->register();
Next Steps#Copied!
Congratulations! You've created your first MilliRules rule. Now you're ready to explore more advanced features:
Learn Core Concepts#Copied!
- Core Concepts - Understand the architecture and how rules work internally
- Packages System - Learn about the package system and how to use it
- Building Rules - Master the fluent API and advanced rule patterns
Explore Available Features#Copied!
- Operators - Learn about pattern matching and comparison operators
- Placeholders - Use dynamic values in your actions
- Built-in Conditions - Discover all available conditions
Build Custom Components#Copied!
- Custom Conditions - Create your own condition types
- Custom Actions - Build custom action handlers
- Custom Packages - Extend MilliRules with custom packages
Ready to dive deeper? Continue to Core Concepts to understand the fundamental architecture of MilliRules.