Creating a Library of Custom Functions for Common Tasks
Learning Objectives
- Create and use PHP functions
- Understand function parameters and returns
- Master variable scope in functions
- Build reusable code components
Understanding the Challenge
Welcome to this practical session on creating your own function library! As web developers, we often find ourselves writing the same code over and over for common tasks like data validation, formatting, and manipulation. Building a personal function library is like creating your own toolbox that you can carry from project to project, saving time and ensuring consistency.
What We'll Accomplish
By the end of this session, you'll have:
- Created a well-organized PHP function library for common web development tasks
- Implemented functions for string manipulation, data validation, array processing, and more
- Learned how to organize, document, and use custom functions effectively
- Understood how to apply George Polya's problem-solving method to function development
George Polya's 4-Step Problem Solving Method
We'll apply this proven four-step method to our function library development:
Step 1: Understand the Problem
Before writing any code, we need to clearly understand what our function library should do. What common tasks do we need to perform frequently? What types of functions would save us time? What are the inputs and outputs for each function?
Step 2: Devise a Plan
After understanding the requirements, we'll plan our library structure and the individual functions. We'll create a simple whiteboard plan for each function before coding.
Step 3: Execute the Plan
We'll write the code for each function, following our plan and adhering to best practices like proper documentation, error handling, and consistent naming conventions.
Step 4: Look Back / Reflect
After implementing the functions, we'll test them, look for improvements, and refine as needed. We might discover better algorithms, edge cases we didn't consider, or opportunities to make our functions more flexible.
Planning Our Function Library
Let's start by identifying categories of functions we'll need in our library:
Now, let's plan the structure of our function library file:
File Structure: functions_library.php
###CODE_BLOCK_1###
Implementing String Functions
Let's start by building some useful string manipulation functions. First, we'll create a function for generating URL-friendly slugs from titles.
Function: create_slug
Step 1: Understand the Problem
Purpose: Convert a title string into a URL-friendly slug
Input: A string (title)
Output: A lowercase string with spaces replaced by hyphens and special characters removed
Example: "Hello World!" → "hello-world"
Step 2: Devise a Plan
- Convert the string to lowercase
- Remove any special characters and accents
- Replace spaces with hyphens
- Remove any consecutive hyphens
- Trim hyphens from the beginning and end
- Return the cleaned slug
Step 3: Execute the Plan
###CODE_BLOCK_3###
Step 4: Look Back / Reflect
Our function handles basic slug creation well, but there might be some improvements we could make:
- Add an optional parameter to customize the separator (e.g., underscore instead of hyphen)
- Add handling for languages with special characters
- Consider maximum length for SEO purposes
Let's implement an improved version:
###CODE_BLOCK_4###
Function: truncate_text
Step 1: Understand the Problem
Purpose: Truncate text to a specific length without cutting words in half
Input: A string, maximum length, and optional ending
Output: Truncated string with ending (e.g., "...")
Example: "This is a long text" (max 10) → "This is a..."
Step 2: Devise a Plan
- Check if the text is already shorter than the maximum length
- If not, cut the text at the maximum length
- Find the last space before the cut to avoid cutting words
- Add the ending (e.g., "...")
- Return the truncated text
Step 3: Execute the Plan
###CODE_BLOCK_6###
Step 4: Look Back / Reflect
The function works well for basic truncation needs. Some potential improvements:
- Add handling for HTML tags (to avoid cutting tags)
- Consider word count instead of character count
- Add support for preserving whole sentences
Let's add HTML awareness to our function:
###CODE_BLOCK_7###
Implementing Validation Functions
Next, let's create some validation functions for common web form inputs.
Function: validate_email
Step 1: Understand the Problem
Purpose: Validate email addresses with customizable options
Input: An email address string and validation options
Output: Boolean indicating if the email is valid
Example: "user@example.com" → true, "invalid.email" → false
Step 2: Devise a Plan
- Check if the email is not empty
- Use PHP's built-in validation for basic format check
- If required, check for specific domains (e.g., only accept business emails)
- If required, check for disposable email domains
- Return the validation result
Step 3: Execute the Plan
###CODE_BLOCK_9###
Step 4: Look Back / Reflect
Our email validation function provides basic functionality, but there are several improvements we could make:
- Add more comprehensive disposable email domain list (could be loaded from a file)
- Add options for maximum/minimum length checks
- Add option to check if the domain's DNS records include MX entries (to verify if the domain can receive email)
- Return specific error messages instead of just true/false
Function: validate_password
Step 1: Understand the Problem
Purpose: Validate passwords against customizable strength criteria
Input: A password string and validation options
Output: Validation result (boolean or details)
Example: "Passw0rd!" with requirements for min length, uppercase, lowercase, numbers, and special chars
Step 2: Devise a Plan
- Check minimum and maximum length requirements
- Check for required character types (uppercase, lowercase, numbers, special)
- If enabled, check against common password lists
- Return validation result with details if requested
Step 3: Execute the Plan
###CODE_BLOCK_11###
Step 4: Look Back / Reflect
The password validation function provides good customization options, but we could enhance it further:
- Add check for sequential characters (e.g., "123456", "abcdef")
- Add check for repeated characters (e.g., "aaaaaa")
- Add option to check against common password dictionaries
- Add option to calculate and return password strength score
Implementing Array Functions
Now, let's create some useful functions for working with arrays, which are common in web development.
Function: array_to_csv
Step 1: Understand the Problem
Purpose: Convert an array of data to CSV format
Input: Array of data (associative or indexed) and CSV options
Output: CSV string or file
Example: Convert user data array to CSV for export
Step 2: Devise a Plan
- Check if the input is an array
- Determine the CSV headers (use keys from associative array or defaults)
- Create a temporary file handle for CSV writing
- Write headers and data rows
- Return CSV string or save to file based on options
Step 3: Execute the Plan
###CODE_BLOCK_13###
Step 4: Look Back / Reflect
Our CSV conversion function works well, but we could improve it in several ways:
- Add option to include BOM (Byte Order Mark) for Excel compatibility
- Add character encoding options
- Add error handling for file operations
- Add option to stream large datasets to avoid memory issues
Function: array_group_by
Step 1: Understand the Problem
Purpose: Group an array of items by a specific key or property
Input: Array of items and the key to group by
Output: Grouped array with key values as indexes
Example: Group products by category
Step 2: Devise a Plan
- Initialize an empty result array
- Iterate through each item in the input array
- Extract the grouping key value from the item
- Add the item to the appropriate group in the result array
- Return the grouped array
Step 3: Execute the Plan
###CODE_BLOCK_15###
Step 4: Look Back / Reflect
Our grouping function provides good flexibility with key support and callback functions. Possible improvements include:
- Add support for multi-level grouping (group by category, then by price range)
- Add option to preserve or discard keys from the original array
- Add option to sort groups by key
- Add support for grouping by multiple keys simultaneously
Implementing Utility Functions
Finally, let's build some general utility functions that can be useful across different projects.
Function: format_date
Step 1: Understand the Problem
Purpose: Format dates in various styles with locale support
Input: Date string or timestamp, format options, locale
Output: Formatted date string
Example: Format "2025-05-15" as "May 15, 2025" or "15/05/2025"
Step 2: Devise a Plan
- Parse the input date (string, timestamp, or DateTime object)
- Create a DateTime object from the input
- Apply the requested format or use a predefined format style
- Apply locale formatting if requested
- Return the formatted date string
Step 3: Execute the Plan
###CODE_BLOCK_17###
Step 4: Look Back / Reflect
Our date formatting function provides good flexibility, but we could improve it by:
- Adding more predefined formats
- Improving locale support for countries with different date formats
- Adding timezone conversion capabilities
- Providing more granular relative time (e.g., "yesterday", "tomorrow")
Function: format_file_size
Step 1: Understand the Problem
Purpose: Format file sizes in human-readable format
Input: Size in bytes, precision, binary units option
Output: Formatted size string (e.g., "1.5 MB")
Example: Convert 1536000 bytes to "1.5 MB"
Step 2: Devise a Plan
- Define the unit prefixes (KB, MB, GB, etc.)
- Determine the appropriate unit based on size
- Calculate the converted size with the desired precision
- Return the formatted size with the unit
Step 3: Execute the Plan
###CODE_BLOCK_19###
Step 4: Look Back / Reflect
Our file size formatting function is straightforward and effective. Possible improvements:
- Add option to use abbreviated units (K, M, G instead of KB, MB, GB)
- Add localization support for decimal point and thousand separators
- Add option to show or hide space between number and unit
- Add option to display hybrid formats like "1.5GB (1,500,000,000 bytes)"
Organizing Your Function Library
Now that we have created several useful functions, let's organize them into a well-structured library file.
Complete Function Library: functions_library.php
Here's how you might organize your complete function library file:
###CODE_BLOCK_21###
Using Your Function Library
To use your function library in a PHP project, simply include it at the beginning of your scripts:
###CODE_BLOCK_22###
Best Practices for Function Libraries
- Document thoroughly: Include detailed docblocks for all functions
- Use consistent naming: Follow a consistent naming pattern (e.g., snake_case)
- Group related functions: Organize functions by category
- Provide sensible defaults: Make functions flexible with good default values
- Include error handling: Functions should gracefully handle invalid inputs
- Avoid name conflicts: Consider prefixing function names to avoid conflicts
- Test thoroughly: Create test cases for each function
- Version control: Use version control to track changes to your library
- Keep it modular: Break large functions into smaller, reusable components
- Optimize performance: Profile and optimize functions for speed and memory usage
- Consider namespaces: For larger libraries, use PHP namespaces to avoid conflicts
- Version your library: Track changes with version numbers
- Create a README: Document how to use your library
- Make it modular: Consider splitting into multiple files for large libraries
Advanced Organization: Using Namespaces
For larger function libraries, using PHP namespaces can help organize code and avoid naming conflicts. Here's how you might restructure your library using namespaces:
Namespace Structure
With namespaces, you would organize your files like this:
###CODE_BLOCK_23###
Example: MyLibrary/Text/Functions.php
###CODE_BLOCK_25###
Example: MyLibrary/autoload.php
###CODE_BLOCK_27###
Using Namespaced Functions
###CODE_BLOCK_28###
Object-Oriented Approach: Class-Based Libraries
Another approach to organizing your function library is to use classes. This can provide additional benefits like encapsulation, inheritance, and better organization.
Class-Based Implementation Example
Example: StringUtils.php
###CODE_BLOCK_30###
Example: ValidationUtils.php
###CODE_BLOCK_32###
Using Class-Based Utilities
###CODE_BLOCK_33###
Publishing and Sharing Your Library
Once you've developed a useful function library, you might want to share it with others or use it across multiple projects. Here are some approaches:
Personal Repository
Keep your library in a private Git repository that you can clone for each project:
###CODE_BLOCK_51###
Composer Package
For more advanced libraries, create a Composer package:
###CODE_BLOCK_52###
WordPress Plugin
For WordPress-specific functions, create a simple utility plugin:
###CODE_BLOCK_53###
Homework Project: Build Your Custom Function Library
Now it's your turn to build your own custom function library! Follow these steps:
-
Identify Common Tasks
Think about functions that would be useful in your own projects. What tasks do you find yourself doing repeatedly?
-
Plan Your Library Structure
Decide how you want to organize your functions (simple function collection, namespaces, or classes).
-
Implement Core Functions
Create at least 8 useful functions across different categories (string manipulation, validation, arrays, utilities).
-
Document Your Functions
Add clear documentation for each function using PHPDoc comments.
-
Test Your Functions
Create a test script that demonstrates each function with different inputs.
-
Create a README
Write a simple README file explaining how to use your library.
Submission Guidelines
- Submit your library as a ZIP file containing all PHP files and the README
- Include a demo.php file that shows usage examples for each function
- Be prepared to explain your design decisions in the next class session
Grading Criteria
- Functionality (40%): Do the functions work correctly and handle edge cases?
- Code Quality (20%): Is the code well-written, consistent, and efficient?
- Documentation (20%): Are functions clearly documented with parameters and return values?
- Organization (10%): Is the library well-organized and easy to use?
- Creativity (10%): Did you include unique, helpful functions beyond the examples?
Additional Resources
- PHP Manual: User-defined Functions
- PHP Manual: Namespaces
- PHP Manual: Classes and Objects
- PHP The Right Way - Modern PHP best practices
- Composer Package Schema - For publishing your library
- PHPStan - Static analysis tool for improving code quality
Conclusion
Creating your own function library is a valuable exercise that will save you time in future projects and help you develop better coding practices. As you continue to build web applications, your library will grow and evolve, becoming an increasingly powerful tool in your developer toolkit.
Remember to apply George Polya's problem-solving method when developing new functions:
- Understand the Problem: Clearly define what the function should do
- Devise a Plan: Outline the steps or algorithm before coding
- Execute the Plan: Write the function with clean, well-documented code
- Look Back: Test, refine, and improve your functions over time
Happy coding!