1
\$\begingroup\$

I'm writing an application that will be managed by my team, it uses Mustache.php as template engine.

I have a PHP file that makes an array of variables and functions that is passed to the Mustache parser to populate the template.

I even provide a system to override partials of my template to edit the aspect of the application for specific users.

Now I'd like to add a way to allow my team to add custom variables to the array passed to Mustache.php without have to hack the core of my application.

I thought about a little function that checks if a .php file with the name of the user exists and if so, include it after I've generated the array and before I pass it to mustache.

It should looks like:

contents.php:

// my queries
$variables = Array(1,2,3,bla,foo,bar);
if (file_exists($_SERVER['BASE_DIR'] . '/customcontents/'. $username . '.php')) {
 include($_SERVER['BASE_DIR'] . '/customcontents/'. $username . '.php');
}
// Call mustache and pass $variables to it

<username>.php:

// custom queries
$variables = array_merge($variables, $customvariables) 

I'm not sure if this can be a nice solution or if you guys have some better idea.

asked Jan 30, 2014 at 8:39
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I don't know anything about Mustache, so just a note about the code: $_SERVER['BASE_DIR'] . '/customcontents/'. $username . '.php' is duplicated, it could be extracted out to a local variable:

$userFile = $_SERVER['BASE_DIR'] . '/customcontents/' . $username . '.php'
if (file_exists($userFile)) {
 include($userFile);
}

(You might have ideas for a better name.)

Reference: Chapter 6. Composing Methods, Introduce Explaining Variable in Refactoring: Improving the Design of Existing Code by Martin Fowler:

Put the result of the expression, or parts of the expression, in a temporary variable with a name that explains the purpose.

And Clean Code by Robert C. Martin, G19: Use Explanatory Variables.

answered Jan 30, 2014 at 9:24
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.