PHPackages                             imponeer/smarty-db-resource - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. imponeer/smarty-db-resource

ActiveLibrary[Database &amp; ORM](/categories/database)

imponeer/smarty-db-resource
===========================

Smarty plugin that adds DB resource type

v4.0.3(4mo ago)020.6k↓33.3%1MITPHPPHP ^8.3CI failing

Since Feb 7Pushed 1mo ago2 watchersCompare

[ Source](https://github.com/imponeer/smarty-db-resource)[ Packagist](https://packagist.org/packages/imponeer/smarty-db-resource)[ RSS](/packages/imponeer-smarty-db-resource/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (22)Used By (0)

[![License](https://camo.githubusercontent.com/6be931099113b795456fd75997d56e4ac2782738e223c535cba0c9cb8ab1cd65/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f696d706f6e6565722f736d617274792d64622d7265736f757263652e737667)](LICENSE) [![GitHub release](https://camo.githubusercontent.com/73ddef8b9d04c3c1bd0a177e29dcc2645fe97b69056be3ff38c6c4be8a6b06b0/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f696d706f6e6565722f736d617274792d64622d7265736f757263652e737667)](https://github.com/imponeer/smarty-db-resource/releases) [![PHP](https://camo.githubusercontent.com/e93ca1043d258484ea9549abcd35356723aefda94a9fa0bb6b820a2734edf105/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f696d706f6e6565722f736d617274792d64622d7265736f757263652e737667)](http://php.net) [![Packagist](https://camo.githubusercontent.com/463bc481ec7617657f84092b672bf4596083b353f9b728efaff0d972e3d2a657/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f696d706f6e6565722f736d617274792d64622d7265736f757263652e737667)](https://packagist.org/packages/imponeer/smarty-db-resource) [![Smarty version requirement](https://camo.githubusercontent.com/f1d15dfa1ce07952f95504edfe21270327e35467e7715d46e5b8860c990e073f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646570656e64656e63792d762f696d706f6e6565722f736d617274792d64622d7265736f757263652f736d61727479253246736d61727479)](https://smarty-php.github.io)

Smarty DB Resource
==================

[](#smarty-db-resource)

> Database-driven template resource for Smarty

[Smarty](https://smarty.net) resource plugin that enables reading templates directly from a database. This powerful extension allows you to store and manage your Smarty templates in a database instead of the filesystem, providing dynamic template management capabilities.

This plugin is inspired by and similar to [Xoops](https://xoops.org) - [resource.db](https://github.com/XOOPS/XoopsCore25/blob/v2.5.8/htdocs/class/smarty/xoops_plugins/resource.db.php).

Installation
------------

[](#installation)

To install and use this package, we recommend to use [Composer](https://getcomposer.org):

```
composer require imponeer/smarty-db-resource
```

Otherwise, you need to include manually files from `src/` directory.

Database Structure
------------------

[](#database-structure)

This plugin requires a specific database table structure to store template information. The table should contain the following columns:

### Required Columns

[](#required-columns)

Column NameTypeDescriptionTemplate ID`MEDIUMINT UNSIGNED AUTO_INCREMENT`Primary key for the template recordTemplate Set`VARCHAR(50)`Template set identifier (e.g., 'default', 'theme1')Template File`VARCHAR(50)`Template filename (e.g., 'header.tpl', 'footer.tpl')Template Source`TEXT`The actual template source code (optional if using file-based templates)Last Modified`INT UNSIGNED`Unix timestamp of last modificationTemplate Description`VARCHAR(255)`Human-readable description of the templateLast Imported`INT UNSIGNED`Unix timestamp of last importTemplate Type`VARCHAR(20)`Template type identifier### Example Table Schema

[](#example-table-schema)

```
CREATE TABLE `tplfile` (
    `tpl_id` MEDIUMINT UNSIGNED AUTO_INCREMENT,
    `tpl_refid` SMALLINT UNSIGNED NOT NULL DEFAULT '0',
    `tpl_tplset` VARCHAR(50) NOT NULL DEFAULT 'default',
    `tpl_file` VARCHAR(50) NOT NULL DEFAULT '',
    `tpl_desc` VARCHAR(255) NOT NULL DEFAULT '',
    `tpl_lastmodified` INT UNSIGNED NOT NULL DEFAULT '0',
    `tpl_lastimported` INT UNSIGNED NOT NULL DEFAULT '0',
    `tpl_type` VARCHAR(20) NOT NULL DEFAULT '',
    `tpl_source` TEXT,
    PRIMARY KEY (`tpl_id`),
    KEY `tpl_tplset_file` (`tpl_tplset`, `tpl_file`)
);
```

**Note:** Column names are configurable when initializing the plugin, so you can adapt the plugin to your existing database schema.

PDO Driver Support
------------------

[](#pdo-driver-support)

This plugin supports multiple database systems through PDO drivers. The plugin automatically selects the appropriate driver based on your PDO connection:

- **SQLite**: Uses optimized SQLite-specific queries
- **All others**: Uses MySQL-compatible queries (works with most SQL databases)

Setup
-----

[](#setup)

To register the database resource with Smarty, use the [`registerResource` function](https://www.smarty.net/docs/en/api.register.resource.tpl):

```
use Imponeer\Smarty\Extensions\DatabaseResource\DatabaseResource;

// Create a Smarty instance
$smarty = new \Smarty\Smarty();

// Create PDO connection
$pdo = new PDO('mysql:host=localhost;dbname=your_database', $username, $password);

// Create and register the database resource
$plugin = new DatabaseResource(
    pdo: $pdo,                                    // PDO database connection
    tplSetName: 'default',                        // Current template set name
    templatesTableName: 'tplfile',                // Table name containing templates
    templateSourceColumnName: 'tpl_source',      // Column containing template source
    templateModificationColumnName: 'tpl_lastmodified', // Column with modification timestamp
    tplSetColumnName: 'tpl_tplset',              // Column identifying template set
    templateNameColumnName: 'tpl_file',          // Column containing template filename
    templatePathGetter: function (array $row): ?string { // Function to get file path from DB row
        return __DIR__ . '/templates/' . $row['tpl_file'];
    },
    defaultTplSetName: 'default'                  // Default template set fallback
);

$smarty->registerResource('db', $plugin);
```

### Custom Database Schema

[](#custom-database-schema)

You can adapt the plugin to your existing database schema by configuring the column names:

```
$plugin = new DatabaseResource(
    pdo: $pdo,
    tplSetName: 'my_theme',
    templatesTableName: 'custom_templates',       // Your table name
    templateSourceColumnName: 'template_content', // Your source column
    templateModificationColumnName: 'modified_at', // Your timestamp column
    tplSetColumnName: 'theme_name',               // Your template set column
    templateNameColumnName: 'filename',          // Your filename column
    templatePathGetter: function (array $row): ?string {
        // Custom logic for file path resolution
        return '/path/to/templates/' . $row['filename'];
    },
    defaultTplSetName: 'default_theme'
);
```

### Template Path Resolution Examples

[](#template-path-resolution-examples)

The `templatePathGetter` function allows you to customize how database records are converted to file paths:

```
// Simple file path concatenation
$templatePathGetter = function (array $row): ?string {
    return __DIR__ . '/templates/' . $row['tpl_file'];
};

// Subdirectory organization by template type
$templatePathGetter = function (array $row): ?string {
    $subdir = $row['tpl_type'] ?? 'default';
    return __DIR__ . '/templates/' . $subdir . '/' . $row['tpl_file'];
};

// Conditional file resolution with validation
$templatePathGetter = function (array $row): ?string {
    if (empty($row['tpl_file'])) {
        return null; // No file path available
    }

    $basePath = __DIR__ . '/templates/';
    $filePath = $basePath . $row['tpl_file'];

    return is_file($filePath) ? $filePath : null;
};
```

### Using the Built-in TemplatePathResolver

[](#using-the-built-in-templatepathresolver)

The package includes a built-in `TemplatePathResolver` class that provides a clean, object-oriented alternative to closures for template path resolution:

```
use Imponeer\Smarty\Extensions\DatabaseResource\Resolver\TemplatePathResolver;

// Create the resolver with your template base path
$templatePathResolver = new TemplatePathResolver('/path/to/templates');

// Use it in DatabaseResource
$plugin = new DatabaseResource(
    pdo: $pdo,
    tplSetName: 'default',
    templatesTableName: 'tplfile',
    templateSourceColumnName: 'tpl_source',
    templateModificationColumnName: 'tpl_lastmodified',
    tplSetColumnName: 'tpl_tplset',
    templateNameColumnName: 'tpl_file',
    templatePathGetter: $templatePathResolver,
    defaultTplSetName: 'default'
);
```

#### Custom Template File Column

[](#custom-template-file-column)

You can also specify a custom column name for the template filename:

```
// Use a custom column name for template files
$templatePathResolver = new TemplatePathResolver(
    templateBasePath: '/path/to/templates',
    templateFileColumn: 'custom_filename_column'
);
```

### Using with Symfony Container

[](#using-with-symfony-container)

To integrate with Symfony, you can leverage autowiring, which is the recommended approach for modern Symfony applications:

```
# config/services.yaml
services:
    # Enable autowiring and autoconfiguration
    _defaults:
        autowire: true
        autoconfigure: true

    # Register your application's services
    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Tests,Kernel.php}'

    # Configure PDO connection
    PDO:
        arguments:
            $dsn: '%env(DATABASE_URL)%'
            $username: '%env(DB_USERNAME)%'
            $password: '%env(DB_PASSWORD)%'

    # Configure template path resolver
    Imponeer\Smarty\Extensions\DatabaseResource\Resolver\TemplatePathResolver:
        arguments:
            $templateBasePath: '%kernel.project_dir%/templates'

    # Configure DatabaseResource
    Imponeer\Smarty\Extensions\DatabaseResource\DatabaseResource:
        arguments:
            $pdo: '@PDO'
            $tplSetName: 'default'
            $templatesTableName: 'tplfile'
            $templateSourceColumnName: 'tpl_source'
            $templateModificationColumnName: 'tpl_lastmodified'
            $tplSetColumnName: 'tpl_tplset'
            $templateNameColumnName: 'tpl_file'
            $templatePathGetter: '@Imponeer\Smarty\Extensions\DatabaseResource\Resolver\TemplatePathResolver'
            $defaultTplSetName: 'default'

    # Configure Smarty with the extension
    Smarty\Smarty:
        calls:
            - [registerResource, ['db', '@Imponeer\Smarty\Extensions\DatabaseResource\DatabaseResource']]
```

Then in your application code:

```
// Get the Smarty instance with the database resource already registered
$smarty = $container->get(\Smarty\Smarty::class);
```

### Using with PHP-DI

[](#using-with-php-di)

With PHP-DI container, you can take advantage of autowiring for a clean configuration:

```
use function DI\create;
use function DI\get;
use function DI\factory;
use Imponeer\Smarty\Extensions\DatabaseResource\Resolver\TemplatePathResolver;

return [
    // Configure PDO
    PDO::class => factory(function () {
        return new PDO('mysql:host=localhost;dbname=your_database', $username, $password);
    }),

    // Configure TemplatePathResolver
    TemplatePathResolver::class => create()
        ->constructor(__DIR__ . '/templates'),

    // Configure DatabaseResource
    \Imponeer\Smarty\Extensions\DatabaseResource\DatabaseResource::class => create()
        ->constructor(
            get(PDO::class),
            'default',                    // tplSetName
            'tplfile',                   // templatesTableName
            'tpl_source',                // templateSourceColumnName
            'tpl_lastmodified',          // templateModificationColumnName
            'tpl_tplset',                // tplSetColumnName
            'tpl_file',                  // templateNameColumnName
            get(TemplatePathResolver::class), // templatePathGetter
            'default'                    // defaultTplSetName
        ),

    // Configure Smarty with the database resource
    \Smarty\Smarty::class => create()
        ->method('registerResource', 'db', get(\Imponeer\Smarty\Extensions\DatabaseResource\DatabaseResource::class))
];
```

Then in your application code:

```
// Get the configured Smarty instance
$smarty = $container->get(\Smarty\Smarty::class);
```

### Using with League Container

[](#using-with-league-container)

If you're using League Container, you can register the extension like this:

```
use League\Container\Container;
use Imponeer\Smarty\Extensions\DatabaseResource\DatabaseResource;
use Imponeer\Smarty\Extensions\DatabaseResource\Resolver\TemplatePathResolver;

// Create the container
$container = new Container();

// Register PDO
$container->add(PDO::class, function() {
    return new PDO('mysql:host=localhost;dbname=your_database', $username, $password);
});

// Register TemplatePathResolver
$container->add(TemplatePathResolver::class, function() {
    return new TemplatePathResolver(__DIR__ . '/templates');
});

// Register DatabaseResource
$container->add(DatabaseResource::class, function() use ($container) {
    return new DatabaseResource(
        pdo: $container->get(PDO::class),
        tplSetName: 'default',
        templatesTableName: 'tplfile',
        templateSourceColumnName: 'tpl_source',
        templateModificationColumnName: 'tpl_lastmodified',
        tplSetColumnName: 'tpl_tplset',
        templateNameColumnName: 'tpl_file',
        templatePathGetter: $container->get(TemplatePathResolver::class),
        defaultTplSetName: 'default'
    );
});

// Register Smarty with the database resource
$container->add(\Smarty\Smarty::class, function() use ($container) {
    $smarty = new \Smarty\Smarty();
    // Configure Smarty...

    // Register the database resource
    $smarty->registerResource('db', $container->get(DatabaseResource::class));

    return $smarty;
});
```

Then in your application code:

```
// Get the configured Smarty instance
$smarty = $container->get(\Smarty\Smarty::class);
```

Usage
-----

[](#usage)

### Basic Template Inclusion

[](#basic-template-inclusion)

To use database-stored templates in your Smarty templates, use the `db:` prefix when referencing template files:

```
{* Include a template from the database *}
{include file="db:header.tpl"}

{* Include with subdirectory structure *}
{include file="db:layouts/main.tpl"}

{* Include with variables *}
{include file="db:user/profile.tpl" user=$currentUser}
```

### Template Examples

[](#template-examples)

#### Main Layout Template

[](#main-layout-template)

```
{* File: db:layout.tpl *}

    {$pageTitle|default:"My Website"}
    {include file="db:includes/head.tpl"}

    {include file="db:includes/header.tpl"}

        {$content}

    {include file="db:includes/footer.tpl"}

```

#### Dynamic Content Loading

[](#dynamic-content-loading)

```
{* Load different templates based on conditions *}
{if $userType == 'admin'}
    {include file="db:admin/dashboard.tpl"}
{else}
    {include file="db:user/dashboard.tpl"}
{/if}

{* Loop through template sections *}
{foreach $sections as $section}
    {include file="db:sections/{$section.template}" data=$section.data}
{/foreach}
```

### Template Set Management

[](#template-set-management)

The plugin supports multiple template sets, allowing you to have different themes or versions:

```
// Switch to a different template set
$plugin = new DBResource(
    pdo: $pdo,
    tplSetName: 'mobile_theme',  // Use mobile-specific templates
    // ... other parameters
);
```

Templates are resolved with fallback logic:

1. First, look for templates in the specified template set
2. If not found, fall back to the default template set
3. If still not found, attempt to load from filesystem (if `templatePathGetter` is configured)

Development
-----------

[](#development)

### Code Quality Tools

[](#code-quality-tools)

This project uses several tools to ensure code quality:

- **PHPUnit** - For unit testing

    ```
    composer test
    ```
- **PHP CodeSniffer** - For coding standards (PSR-12)

    ```
    composer phpcs    # Check code style
    composer phpcbf   # Fix code style issues automatically
    ```
- **PHPStan** - For static analysis

    ```
    composer phpstan
    ```

### Running Tests

[](#running-tests)

The test suite includes comprehensive tests for database operations and template resolution:

```
# Run all tests
composer test

# Run tests with coverage
vendor/bin/phpunit --coverage-html coverage/
```

Documentation
-------------

[](#documentation)

API documentation is automatically generated and available in the project's wiki. For more detailed information about the classes and methods, please refer to the [project wiki](https://github.com/imponeer/smarty-db-resource/wiki).

Contributing
------------

[](#contributing)

Contributions are welcome! Here's how you can contribute:

1. **Fork the repository**
2. **Create a feature branch**: `git checkout -b feature-name`
3. **Commit your changes**: `git commit -am 'Add some feature'`
4. **Push to the branch**: `git push origin feature-name`
5. **Submit a pull request**

### Contribution Guidelines

[](#contribution-guidelines)

- **Follow PSR-12 coding standards** - Use `composer phpcs` to check your code
- **Write tests** - Include unit tests for any new features or bug fixes
- **Update documentation** - Update README.md and inline documentation as needed
- **Test thoroughly** - Ensure your changes work with all supported database systems

### Reporting Issues

[](#reporting-issues)

If you find a bug or have a feature request, please create an issue in the [issue tracker](https://github.com/imponeer/smarty-db-resource/issues).

When reporting bugs, please include:

- PHP version
- Database system and version
- Smarty version
- Steps to reproduce the issue
- Expected vs actual behavior

### Development Setup

[](#development-setup)

1. Clone the repository
2. Install dependencies: `composer install`
3. Run tests: `composer test`
4. Check code style: `composer phpcs`
5. Run static analysis: `composer phpstan`

###  Health Score

54

—

FairBetter than 97% of packages

Maintenance83

Actively maintained with recent releases

Popularity25

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity77

Established project with proven stability

 Bus Factor1

Top contributor holds 63.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~94 days

Recently: every ~213 days

Total

20

Last Release

133d ago

Major Versions

v1.1 → v2.02021-10-27

v2.1.5 → v3.0.02023-02-01

v3.0.6 → v4.0.02025-07-27

PHP version history (3 changes)v1.0.0PHP &gt;=7.1

v3.0.0PHP ^7.3|^8.0

v4.0.0PHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/dba53e399a507d1f60626164c8b1e340a5cc0dc4f0637f4c6aaff8fc239fdaee?d=identicon)[fiammybe](/maintainers/fiammybe)

![](https://www.gravatar.com/avatar/7255f306e0ca27292c50cdd9644c1c04e0d7b0f54bf35e0cdd79dc55c83b4923?d=identicon)[MekDrop](/maintainers/MekDrop)

![](https://www.gravatar.com/avatar/79009323fafcd4974bb1713b12eea0a610f01c4fb21cc5e85d446c4cb66453d4?d=identicon)[skenow](/maintainers/skenow)

---

Top Contributors

[![MekDrop](https://avatars.githubusercontent.com/u/342641?v=4)](https://github.com/MekDrop "MekDrop (63 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (30 commits)")[![fiammybe](https://avatars.githubusercontent.com/u/3736946?v=4)](https://github.com/fiammybe "fiammybe (3 commits)")[![Codex](https://avatars.githubusercontent.com/in/2248422?v=4)](https://github.com/Codex "Codex (2 commits)")[![mend-bolt-for-github[bot]](https://avatars.githubusercontent.com/in/16809?v=4)](https://github.com/mend-bolt-for-github[bot] "mend-bolt-for-github[bot] (1 commits)")

---

Tags

databasehacktoberfestresourcesmartysmarty-pluginssmarty-resourcedatabasepdosmartysmarty-pluginssmarty-resource

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/imponeer-smarty-db-resource/health.svg)

```
[![Health](https://phpackages.com/badges/imponeer-smarty-db-resource/health.svg)](https://phpackages.com/packages/imponeer-smarty-db-resource)
```

###  Alternatives

[doctrine/dbal

Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.

9.7k578.4M5.6k](/packages/doctrine-dbal)[ifsnop/mysqldump-php

PHP version of mysqldump cli that comes with MySQL

1.3k5.5M69](/packages/ifsnop-mysqldump-php)[nette/database

💾 Nette Database: layer with a familiar PDO-like API but much more powerful. Building queries, advanced joins, drivers for MySQL, PostgreSQL, SQLite, MS SQL Server and Oracle.

5656.7M234](/packages/nette-database)[dibi/dibi

Dibi is Database Abstraction Library for PHP

5013.8M120](/packages/dibi-dibi)[aura/sqlquery

Object-oriented query builders for MySQL, Postgres, SQLite, and SQLServer; can be used with any database connection library.

4572.9M34](/packages/aura-sqlquery)[envms/fluentpdo

FluentPDO is a quick and light PHP library for rapid query building. It features a smart join builder, which automatically creates table joins.

925511.7k13](/packages/envms-fluentpdo)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
