Skip to content
Advertisement

PHP Custom ‘MVC’: Including ‘modules’ that contain HTML/CSS/JS the right way

I have created my custom PHP ‘MVC’, if you’d call it that, with a structure that treats pages and certain components as ‘modules’, by storing them in their own folders that include any code related to the ‘modules’. Modules look roughly like this:

├── popup/
│   ├── popup.css
│   ├── popup.js
│   └── popup.php
└── home/
    ├── index.php
    ├── css
    │   └── style.css
    ├── js
    │   └── script.js
    └── html
        └── layout.php

I find this structure much better to work with, and apparently this guy does as well: Lay Out Your Code Like You’d Lay Out Your House

The popup is a component that can be added to a view, and home is a view (I’m not storing them in the same location, but have simplified the structure just for the sake of this example).

I want to be able to easily include the popup component in the views that it’s used. What I’m doing now is including the CSS, JS and HTML separately, like this:

on home/css/style.css:
@import "../../popup/popup.css"

on home/js/script.js:
// @codekit-prepend '../../popup/popup.js';

on home/html/layout.php:
include '../../popup/popup.php';

The perfect case scenario in my head is to be able to include the popup component with a one liner on each view, similar to including a PHP library. Is there a right way to do this?

I previously rendered the popup‘s CSS and JS inside the html document using link and script, so I could include the complete module by just including popup.php. This increases the number of external CSS and JS files the document has to load. The legend also has it that it’s better to include a single large CSS/JS file than to include many small ones. Is this still valid in 2020?

Advertisement

Answer

Re: “legend has it”: bundling and minification will reduce the overhead of multiple requests and the overall byte count.

The other part of your question – the “how do I simplify module usage” – is probably going to involve beefing up your MVC code base. What you might want to be doing is that each module has a core file or routine that will be called by your base code .. include_me.php or class::bootstrap(&$theApp) .. your mileage may vary – then inside the parts where CSS and JS is meant to be included you walk through theApp-arrays like $pageCSS, $headJS and $bodyJS and in the appropriate places include all the files that the include_me/bootstrap routines placed into those arrays.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement