Honza Černý
Posted on June 22, 2024
Using PhpStorm’s File Templates makes it easier to create linked files in frameworks like presenters/controlers and their templates. By setting up custom templates, you can quickly generate these files with the right structure. Using Velocity variables like ${NAME}
and ${DIR_PATH}
can helps automatically create file names and paths, reducing mistakes.
🜁
In my case, I use the Nette Framework. There is a Presenter (HomepagePresenter.php) connected with a Template (Homepage.default.latte) in a Module (Admin):
/app/modules/Admin/Homepage/templates/Homepage.default
/app/modules/Admin/Homepage/HomepagePresenter.php
I want a File Template that asks for just one name and prepares everything else 💥
- Go to: Settings → Editor → File and Code Templates
- Create a new Template and use the variable
${NAME}
🜛
use variables in both the code and the path
For the second file, use “Create Child Template File”🜔
We can create another variable named ${MODULE}
for setting the namespace like this:
namespace App\\${MODULE}Module\Presenters;
But ...
🜇 / 🜂 = 🜸 + 🜍🜞
when you study a little bit of Velocity templates and the variables that PhpStorm provides, you can combine them to automate some processes.
In Velocity, #set
is used for variable settings, and PhpStorm suggests the variable ${DIR_PATH}
– the path to the directory of the new file (relative to the project root).
So we can start our Presenter template with this power 🜣 and use new variable ${moduleName}
in the code.
#set($dirPath = ${DIR_PATH})
#set($parentDirPath = $dirPath.substring(0, $dirPath.lastIndexOf("/")))
#set($moduleName = $parentDirPath.substring($parentDirPath.lastIndexOf("/") + 1))
<?php
namespace App\\${moduleName}Module\Presenters;
And that’s it. Just a few lines of Velocity and more automated creation of File Templates is done. There is no magic, just digital alchemy 👨🔬⚗️
Posted on June 22, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.