Skip to main content

Course Progress

Loading...

Creating a Library of Custom Functions for Common Tasks

Duration: 90 minutes
Module 2: Functions in PHP

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

Diagram
Improve > C[3. Execute the Plan] C 1. Understand the Problem 2. Devise a Plan 3. Execute the Plan 4. Look Back / Reflect

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:

PHP Function Library Categories String Functions - Text formatting - String validation - Text transformation Validation Functions - Form input validation - Data type checking - Security validation Array Functions - Array manipulation - Data extraction - Array formatting Utility Functions - Date formatting - URL processing - File handling

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

  1. Convert the string to lowercase
  2. Remove any special characters and accents
  3. Replace spaces with hyphens
  4. Remove any consecutive hyphens
  5. Trim hyphens from the beginning and end
  6. 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

  1. Check if the text is already shorter than the maximum length
  2. If not, cut the text at the maximum length
  3. Find the last space before the cut to avoid cutting words
  4. Add the ending (e.g., "...")
  5. 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

  1. Check if the email is not empty
  2. Use PHP's built-in validation for basic format check
  3. If required, check for specific domains (e.g., only accept business emails)
  4. If required, check for disposable email domains
  5. 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

  1. Check minimum and maximum length requirements
  2. Check for required character types (uppercase, lowercase, numbers, special)
  3. If enabled, check against common password lists
  4. 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

  1. Check if the input is an array
  2. Determine the CSV headers (use keys from associative array or defaults)
  3. Create a temporary file handle for CSV writing
  4. Write headers and data rows
  5. 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

  1. Initialize an empty result array
  2. Iterate through each item in the input array
  3. Extract the grouping key value from the item
  4. Add the item to the appropriate group in the result array
  5. 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

  1. Parse the input date (string, timestamp, or DateTime object)
  2. Create a DateTime object from the input
  3. Apply the requested format or use a predefined format style
  4. Apply locale formatting if requested
  5. 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

  1. Define the unit prefixes (KB, MB, GB, etc.)
  2. Determine the appropriate unit based on size
  3. Calculate the converted size with the desired precision
  4. 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.

Diagram
> C[Validation Functions] A > E[Utility Functions] B > B2[truncate_text()] C > C2[validate_password()] D > D2[array_group_by()] E functions_library.php String Functions Validation Functions Array Functions Utility Functions create_slug() truncate_text() validate_email() validate_password() array_to_csv() array_group_by() format_date() format_file_size()

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:

Diagram
> C[MyLibrary\\Validation] A > E[MyLibrary\Utils] B > B2[truncateText()] C > C2[validatePassword()] D > D2[groupBy()] E MyLibrary MyLibrary\Text MyLibrary\\Validation MyLibrary\\Arrays MyLibrary\Utils createSlug() truncateText() validateEmail() validatePassword() toCsv() groupBy() formatDate() formatFileSize()

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 Library Structure StringUtils + static createSlug($string, $separator = '-') + static truncateText($text, $maxLength) + static sanitize($string, $allowHtml = false) ValidationUtils + static validateEmail($email, $options = []) + static validatePassword($password, $options = []) + static isValidUrl($url) FormatUtils + static formatDate($date, $format = 'default') + static formatFileSize($bytes, $precision = 2) + static formatCurrency($amount, $currency = 'USD')

Class-Based Implementation Example

Example: StringUtils.php

###CODE_BLOCK_30###

Example: ValidationUtils.php

###CODE_BLOCK_32###

Using Class-Based Utilities

###CODE_BLOCK_33###

Expanding Your Function Library

As you continue to develop websites and applications, you'll identify more common tasks that can be automated with custom functions. Here are some ideas for additional functions you might add to your library:

Diagram
(Function LibraryExpansion fa fa-globe

Security Functions

  • generate_csrf_token() - Generate and validate CSRF tokens for forms
  • encrypt_data() / decrypt_data() - Simple data encryption/decryption
  • sanitize_input() - Comprehensive input sanitization for different data types
  • generate_secure_password() - Generate secure random passwords

Image Processing Functions

  • resize_image() - Resize images while maintaining aspect ratio
  • add_watermark() - Add text or image watermarks to images
  • optimize_image() - Compress images for web use
  • convert_image_format() - Convert between image formats (JPG, PNG, WebP)

Database Utility Functions

  • paginate_results() - Handle pagination for database queries
  • build_where_clause() - Build SQL WHERE clauses from array conditions
  • sanitize_sql() - Sanitize SQL queries to prevent injection
  • cache_query_results() - Cache and retrieve database query results

API Interaction Functions

  • make_api_request() - Wrapper for API requests with error handling
  • parse_api_response() - Parse and sanitize API responses
  • handle_rate_limiting() - Handle API rate limiting with backoff
  • create_oauth_signature() - Generate OAuth signatures for API authentication

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:

  1. Identify Common Tasks

    Think about functions that would be useful in your own projects. What tasks do you find yourself doing repeatedly?

  2. Plan Your Library Structure

    Decide how you want to organize your functions (simple function collection, namespaces, or classes).

  3. Implement Core Functions

    Create at least 8 useful functions across different categories (string manipulation, validation, arrays, utilities).

  4. Document Your Functions

    Add clear documentation for each function using PHPDoc comments.

  5. Test Your Functions

    Create a test script that demonstrates each function with different inputs.

  6. 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

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:

  1. Understand the Problem: Clearly define what the function should do
  2. Devise a Plan: Outline the steps or algorithm before coding
  3. Execute the Plan: Write the function with clean, well-documented code
  4. Look Back: Test, refine, and improve your functions over time

Happy coding!