Repository navigation
[Smarty 5.x] Assign custom resource‘s DB template metadata to Smarty directly? #1163
|
I feel like this must be super simple, but I am lost even with the documentation and the (simple) examples. I have a custom resource registered that loads Templates from the MySql DB. What I need is however not only to process the Smarty Template Source retrieved, but my Layout Wrapper must have all related Metadata stored along the template.
Simplifies Example: <?php
use Smarty\Resource\CustomPlugin;
class DbTemplateResource extends CustomPlugin
{
protected PDO $pdo;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
protected function fetch($name, &$source, &$mtime)
{
$sql = "
SELECT
template_source,
id,
created,
parent_id
FROM smarty_templates
WHERE name = :name
LIMIT 1
";
$stmt = $this->pdo->prepare($sql);
$stmt->execute([':name' => $name]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
throw new SmartyException("Template '{$name}' not found in database");
}
// template source
$source = $row['template_source'];
// modification time for Smarty caching
$mtime = strtotime($row['created']);
}
}
// PDO connection
$pdo = new PDO(
'mysql:host=localhost;dbname=app;charset=utf8mb4',
'user',
'password',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
// register resource
$smarty->registerResource('db', new DbTemplateResource($pdo));
// usage:
$smarty->display('db:home');Usually of course i can do Thanks for any suggestions! |
Answered by
oliveratgithub
Jan 4, 2026
Replies: 1 comment 1 reply
|
You could do the query in a separate class and "remember" the result if you must. But I wouldn't worry about doing 2 queries. MySQL is extremely efficient, especially if you perform the exact same query twice. |
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @wisskid, I came to the same conclusion when going over the implementation again : as a custom Class Object is registered as the resource handler, the DB-query result can be passed as Dependency 👍 This also allows me to assign the Template information retrieved to both, my PHP app and Smarty Vars.
My concern was not really on performance, but more from an architectural standpoint; I find it confusing when same queries are executed in different parts.
The solution, abstracted for example purpose, looks something like this: