承接 takuya-motoshima/codeigniter-extension 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

takuya-motoshima/codeigniter-extension

最新稳定版本:5.0.4

Composer 安装命令:

composer require takuya-motoshima/codeigniter-extension

包简介

Extend CodeIgniter for ease of use

README 文档

README

PHP Version License Packagist Downloads Latest Version

日本語 | Changelog | 変更履歴

An enhanced CodeIgniter 3 package providing extended core classes (controllers, models, views) and utility classes.

Table of Contents

Features

Core Extensions

  • Enhanced Controllers - JSON response, template rendering, access control
  • Advanced Models - Query caching, batch operations, helper methods
  • Enhanced Router - Annotation-based access control

Utility Classes

  • Image Processing - Resize, crop, format conversion, GIF frame extraction, PDF to image
  • Video Processing - Video file manipulation and conversion
  • File Operations - Advanced file and directory operations with locking
  • CSV Handling - Import/export utilities
  • Email - Template-based emails, Amazon SES integration
  • REST Client - HTTP client for API integrations
  • Security - Encryption/decryption, IP validation
  • Validation - Custom rules (hostname, IP, CIDR, datetime, paths)
  • Session Management - Database-backed sessions with custom columns, PHP 7.0+ SessionHandlerInterface compliance
  • Logging - Enhanced logging with context
  • Template Engine - Twig integration with session variables

AWS Integration

  • Amazon Rekognition - Face detection, comparison, and analysis
  • Amazon SES - Reliable email delivery service

Requirements

  • PHP 7.3.0 or later
  • Composer
  • PHP Extensions:
    • php-gd
    • php-mbstring
    • php-xml
    • php-imagick (optional, for GIF operations)

Optional: ImageMagick Installation

Required for extractFirstFrameOfGif method in \X\Util\ImageHelper.

Amazon Linux 2:

sudo yum -y install ImageMagick php-imagick

Amazon Linux 2023:

# Install ImageMagick and PECL
sudo dnf -y install ImageMagick ImageMagick-devel php-pear.noarch

# Install imagick extension
sudo pecl install imagick
echo "extension=imagick.so" | sudo tee -a /etc/php.ini

# Restart services
sudo systemctl restart nginx php-fpm

Installation

Create a new project using Composer:

composer create-project takuya-motoshima/codeigniter-extension myapp
cd myapp

Quick Start

1. Set Permissions

sudo chmod -R 755 public/upload application/{logs,cache,session}
sudo chown -R nginx:nginx public/upload application/{logs,cache,session}

2. Configure Web Server

Copy the Nginx configuration:

sudo cp nginx.sample.conf /etc/nginx/conf.d/myapp.conf
sudo systemctl restart nginx

3. Set Up Database

Import the database schema:

mysql -u root -p your_database < skeleton/init.sql

4. Build Frontend Assets

cd client
npm install
npm run build

5. Access Application

Open http://{your-server-ip}:3000/ in your browser.

Default Credentials:

  • Email: robin@example.com
  • Password: password

Screenshots

Sign In User List

Configuration

Basic Config (application/config/config.php)

Setting Default Recommended
base_url empty if (!empty($_SERVER['HTTP_HOST'])) $config['base_url'] = '//' . $_SERVER['HTTP_HOST'] . str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
enable_hooks FALSE TRUE
permitted_uri_chars a-z 0-9~%.:_\- a-z 0-9~%.:_\-,
sess_save_path NULL APPPATH . 'session';
cookie_httponly FALSE TRUE
composer_autoload FALSE realpath(APPPATH . '../vendor/autoload.php');
index_page index.php empty

Access Control Setup

1. Define Default Route

In application/config/routes.php:

$route['default_controller'] = 'users/login';

2. Set Session Constant

In application/config/constants.php:

const SESSION_NAME = 'session';

3. Configure Hooks

In application/config/hooks.php:

use \X\Annotation\AnnotationReader;
use \X\Util\Logger;

$hook['post_controller_constructor'] = function() {
  if (is_cli()) return;

  $CI =& get_instance();
  $meta = AnnotationReader::getAccessibility($CI->router->class, $CI->router->method);
  $loggedin = !empty($_SESSION[SESSION_NAME]);

  if (!$meta->allow_http)
    throw new \RuntimeException('HTTP access is not allowed');
  else if ($loggedin && !$meta->allow_login)
    redirect('/users/index');
  else if (!$loggedin && !$meta->allow_logoff)
    redirect('/users/login');
};

$hook['pre_system'] = function () {
  $dotenv = Dotenv\Dotenv::createImmutable(ENV_DIR);
  $dotenv->load();
  set_exception_handler(function ($e) {
    Logger::error($e);
    show_error($e->getMessage(), 500);
  });
};

Session Management

The package extends CodeIgniter's database session driver with PHP 7.0+ SessionHandlerInterface compatibility:

Features:

  • Custom Session Columns - Store additional data (e.g., email, user_id) directly in session table
  • updateTimestamp Implementation - Complies with PHP 7.0+ SessionHandlerInterface requirements
  • No Warning Logs - Prevents "Failed to write session data" warnings in PHP 7.0+

Configuration (application/config/config.php):

$config['sess_driver'] = 'database';
$config['sess_save_path'] = 'session';
$config['sess_table_additional_columns'] = ['email'];

Technical Details:

The SessionDatabaseDriver class implements the updateTimestamp() method required by PHP 7.0+'s SessionHandlerInterface. This prevents PHP from falling back to the default file handler, which causes warnings like:

Warning: session_write_close(): Failed to write session data using user defined save handler.

For more information, see the PHP SessionHandlerInterface documentation.

Architecture

Directory Structure

src/X/
├── Annotation/          # Access control annotations
│   ├── Access.php           # @Access annotation definition
│   └── AnnotationReader.php # Annotation parser
├── Composer/            # Composer installer
│   └── Installer.php        # Post create-project handler
├── Constant/            # Constants
│   ├── Environment.php      # Environment constants (DEVELOPMENT, TESTING, PRODUCTION)
│   └── HttpStatus.php       # HTTP status code constants
├── Controller/          # Controller extensions
│   └── Controller.php       # Base controller with response helpers
├── Core/                # CodeIgniter core extensions
│   ├── Loader.php           # Extended loader
│   ├── Router.php           # Extended router
│   └── URI.php              # Extended URI
├── Database/            # Database extensions
│   ├── DB.php               # DB factory
│   ├── Driver.php           # Base driver
│   ├── QueryBuilder.php     # Extended query builder
│   └── Result.php           # Extended result set
├── Exception/           # Custom exceptions
│   ├── AccessDeniedException.php
│   └── RestClientException.php
├── Hook/                # Hooks
│   └── Authenticate.php     # Authentication hook
├── Library/             # Library extensions
│   ├── FormValidation.php   # Extended form validation
│   ├── Input.php            # Extended input library
│   ├── Router.php           # Router library
│   └── SessionDatabaseDriver.php # Database session driver (PHP 7.0+)
├── Model/               # Model extensions
│   ├── Model.php            # Base model with query builder
│   ├── AddressModel.php     # Address model
│   ├── SessionModel.php     # Session model
│   └── SessionModelInterface.php
├── Rekognition/         # AWS Rekognition
│   └── Client.php           # Face detection/comparison client
└── Util/                # Utility classes (21 classes)
    ├── AmazonSesClient.php  # Amazon SES email
    ├── ArrayHelper.php      # Array operations
    ├── Cipher.php           # Encryption (AES-256-CTR)
    ├── CsvHelper.php        # CSV import/export
    ├── DateHelper.php       # Date operations
    ├── EMail.php            # Email with templates
    ├── FileHelper.php       # File/directory operations
    ├── HtmlHelper.php       # HTML utilities
    ├── HttpInput.php        # HTTP input processing
    ├── HttpResponse.php     # HTTP response builder
    ├── ImageHelper.php      # Image processing
    ├── IpUtils.php          # IP address utilities
    ├── Iterator.php         # Combinatorics
    ├── Loader.php           # Resource loader
    ├── Logger.php           # Logging
    ├── RestClient.php       # REST API client
    ├── SessionHelper.php    # Session utilities
    ├── StringHelper.php     # String operations
    ├── Template.php         # Twig integration
    ├── UrlHelper.php        # URL utilities
    ├── Validation.php       # Data validation
    └── VideoHelper.php      # Video processing

Application Structure (skeleton/)

Projects created with this package follow this structure:

application/
├── core/
│   ├── AppController.php    # Extends \X\Controller\Controller
│   └── AppModel.php         # Extends \X\Model\Model
├── config/
│   ├── hooks.php            # Access control via AnnotationReader
│   └── constants.php        # SESSION_NAME, ENV_DIR constants
├── controllers/             # Application controllers
├── models/                  # Application models
└── views/                   # Twig templates

Usage Examples

Controllers

use \X\Annotation\Access;

class Users extends AppController {
  /**
   * @Access(allow_login=true, allow_logoff=false, allow_role="admin")
   */
  public function index() {
    $users = $this->UserModel->get()->result_array();
    parent::set('users', $users)->view('users/index');
  }

  /**
   * @Access(allow_http=true)
   */
  public function api() {
    $data = ['message' => 'Success'];
    parent::set($data)->json();
  }
}

Models

class UserModel extends AppModel {
  const TABLE = 'user';

  public function getActiveUsers() {
    return $this
      ->where('active', 1)
      ->order_by('name', 'ASC')
      ->get()
      ->result_array();
  }
}

Twig Templates

Session variables are automatically available:

// PHP
$_SESSION['user'] = ['name' => 'John Smith', 'role' => 'admin'];
{# Template #}
{% if session.user is defined %}
  <p>Welcome, {{ session.user.name }}!</p>
  {% if session.user.role == 'admin' %}
    <a href="/admin">Admin Panel</a>
  {% endif %}
{% endif %}

Using Utilities

// Image processing
use \X\Util\ImageHelper;
ImageHelper::resize('/path/to/image.jpg', '/path/to/output.jpg', 800, 600);

// File operations
use \X\Util\FileHelper;
FileHelper::makeDirectory('/path/to/dir', 0755);

// Encryption
use \X\Util\Cipher;
$encrypted = Cipher::encrypt('secret data', 'encryption-key');

// REST client
use \X\Util\RestClient;
$client = new RestClient(['base_url' => 'https://api.example.com']);
$response = $client->get('/users');

API Reference

Controller Methods

Method Description
json() Send JSON response
view($template) Render Twig template
html($html) Send HTML response
text($text) Send plain text response
image($path) Send image response
download($filename, $content) Force file download
set($key, $value) Set response data
setCorsHeader($origin) Set CORS headers

Model Methods

Method Description
get_all() Get all records
get_by_id($id) Get record by ID
count_by_id($id) Count records by ID
exists_by_id($id) Check if record exists
insert_on_duplicate_update() INSERT ... ON DUPLICATE KEY UPDATE
insert_on_duplicate_update_batch() Batch upsert

Utility Classes

Class Key Methods
ImageHelper resize(), crop(), writeDataURLToFile(), pdf2Image()
FileHelper makeDirectory(), delete(), copyFile(), move()
Cipher encrypt(), decrypt(), encode_sha256()
RestClient get(), post(), put(), delete()
Logger debug(), info(), error(), display()
Validation hostname(), ipaddress(), email(), is_path()
IpUtils isIPv4(), isIPv6(), inRange()
Template load($template, $params)

Troubleshooting

Common Issues

"Failed to write session data" Warning

Problem: PHP 7.0+ shows session write warnings.

Solution: This package includes SessionDatabaseDriver which implements updateTimestamp() for PHP 7.0+ compatibility. Ensure you're using:

$config['sess_driver'] = 'database';

Imagick Extension Not Found

Problem: extractFirstFrameOfGif() throws error.

Solution: Install ImageMagick and php-imagick:

# Amazon Linux 2023
sudo dnf -y install ImageMagick ImageMagick-devel php-pear.noarch
sudo pecl install imagick
echo "extension=imagick.so" | sudo tee -a /etc/php.ini
sudo systemctl restart php-fpm

Access Annotation Not Working

Problem: @Access annotations are ignored.

Solution:

  1. Enable hooks in config.php: $config['enable_hooks'] = TRUE;
  2. Configure hooks.php with AnnotationReader::getAccessibility()

Template Cache Issues

Problem: Twig templates not updating.

Solution: Clear the cache directory:

rm -rf application/cache/templates/*

Testing

Run unit tests:

composer test

Test files are located in:

  • __tests__/*.php - Test cases
  • phpunit.xml - Configuration
  • phpunit-printer.yml - Output format

Documentation

Generate PHPDoc

# Download phpDocumentor (one-time)
wget https://phpdoc.org/phpDocumentor.phar
chmod +x phpDocumentor.phar

# Generate docs
php phpDocumentor.phar run -d src/ --ignore vendor --ignore src/X/Database/Driver/ -t docs/

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Author

Takuya Motoshima

License

MIT License

统计信息

  • 总下载量: 5.11k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 6
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 5
  • Watchers: 3
  • Forks: 4
  • 开发语言: JavaScript

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-10-23