The structural design of a PHP application using Javascript and CSS in an MVC framework

My team and I are about to revamp the frontend of a large CakePHP 2 application. Our main aim, apart from giving it a fresh look, is to create more reusable SCSS/Javascript code, establish a logical structure in our frontend code as well as the third-party assets we utilize.

Currently, our CSS modifications are haphazardly added to one file without considering reusability or structure. Similarly, most of our Javascript is embedded within views, lacking organization and reusability.

We do have some functions that are shared across multiple views, but they are all consolidated into one file. Here lies the problem of scalability and maintainability.

Question

So, my question is, what would be an effective structure or architecture for managing Javascript and CSS/SCSS in a CakePHP application? Where should one start?

My ideas

Currently, we do not utilize tools like CSS preprocessors or frontend package managers such as Bower. Implementing a CSS preprocessor like SCSS and exploring the use of Bower for managing third-party assets are on our agenda.

Regarding Javascript, automatically loading a Javascript file based on the CakePHP Controller and action name could help introduce some structure. But how should the code within these files be structured? Should we consider extending a 'master' Javascript object with ready-to-use functions? And for common scripts used across pages, should we opt for separate functions or consolidate them into one reusable object?

Found resources:

How to structure Javascript architecture to complement a PHP MVC web app? => No definitive answer applicable to our scenario was found here.

https://www.sitepoint.com/architecture-in-sass/ => Provided valuable insights on organizing SASS.

JS MV* Frameworks like https://angularjs.org/ => Due to the size of our existing application, adopting a JS MVC framework like AngularJS seems daunting with our current constraints. Further research may be necessary, as these frameworks appear intricate for our project.

Answer №1

Our team utilizes this solution in our workplace and it has proven to be quite effective for us.

Answer №2

To effectively handle the JavaScript needed for the current page, a smart strategy is required. Allow me to present a simplified version of our approach.

Begin by creating a JavaScript file structured like this (Note This is Pseudocode!):

MyApp = {
    init: function(controller, action) {
        // Verify if MyApp.actions.<ControllerName>.<actionName> is defined and execute it.
    }
    actions: {
        ControllerName: {
            actionName: function() {
                // Place any action-specific code here
                $('foo').bar();
            }
        }
    }
}

This concept is essentially "namespacing in the world of JavaScript". You could also opt to create one file per controller/action and append the function/object to the actions property. This method aids in organizing your JS code efficiently. We consolidate and compress all the files into a single JS file that is loaded within your application. To streamline frontend asset management, we utilize npm, bower, and gulp.

In the JS section of your applications' layout.ctp files, call it like this:

MyApp.init(\'' . $this->request->controller. '\',' . $this->request->action'\');

By doing this, the JS related to the specific controller action you've invoked will be automatically triggered if there is a corresponding object in MyApp.actions. The structure of your init method can vary according to your preference.

One vital aspect to keep in mind is avoiding including extensive JS codes that are seldom utilized in your unified minified JS file. For instance, I would refrain from embedding a large script like CkEditor unless it's necessary on most app pages.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Change a function to disregard clicks initiated within the last cell of every row within a table

Currently, I have a JavaScript function in place that operates in the following manner. Upon clicking any row within the table, it leads to a new page at the link indicated on line 6. (The ID# from column 0 is appended to the end of the link). While this ...

What is the best way to display the output of my Sudoku generator as an HTML table in Django?

Recently delving into Django, I've been working on creating a Sudoku web application. To generate the Sudoku puzzles, I developed a Python script named "Sudoku Generator.py" which produces matrices like this: [[3, 8, 2, 7, 5, 6, 1, 4, 9],[1, 4, 5, 2, ...

Struggling with z-index or float issues on Chrome and Safari with CSS styling

Check out my website at I have incorporated the Easy Slider 1.7 plugin from this source and made some custom JavaScript modifications for a banner rotator. The issue I am facing is that on webkit browsers, the navigation links (1,2,3,4,5) on the banner a ...

Deploying static files with Django in a production environment

My Django application is functioning properly on Ubuntu 14.04 with nginx 1.10, Django 1.10.2, and uWSGI 2.0.14. It is able to load static files such as JavaScript, CSS, and images, but the CSS files are not being applied to my website. Below is the configu ...

Using JavaScript to Filter JSON Objects

After making a php ajax call, I have received the following JSON data that needs to be displayed to the users: JSON {"headers":{},"body":"{\"comuni\":[{\"datapresub\":\"08\/08 ...

tracking the number of new buttons pressed (HTML/Javascript)

As a novice in programming, I am currently tackling a task involving a table in otree that displays 256 unique buttons using Javascript. Each button reveals an icon when clicked, thanks to a straightforward function. Within this function, I have incorpora ...

Effortlessly retrieving the id attribute from an HTML tag using jQuery

Currently, I am encountering an issue with a code snippet that is designed to extract the value from an HTML tag. While it successfully retrieves a single word like 'desk', it fails when attempting to do so for an ID consisting of two or more wor ...

Incorporating Mediainfo.js into Angular 8: A Seamless Integration

I'm attempting to utilize Mediainfo.js for retrieving video information on the frontend of my Angular 8 project. However, I am encountering the following errors: GET https://192.168.25.177:4200/MediaInfoModule.wasm 404 (Not Found) wasm streaming compi ...

What could possibly be causing this object parse function to return undefined?

Unfortunately, I am facing issues with object grabbing once again. Even though I can see the JSON object returned from the database perfectly fine in the console, I encounter an "undefined" error when trying to access a child element such as result.bills, ...

Ways to emphasize a specific row within a table for special occasions

I have limited knowledge of CSS and JavaScript, but I am looking for a way to create a notification highlight that functions similarly to when someone comments on a Facebook post. When clicked, it should direct me to the specific comment with a temporary h ...

Switch Image on Hover in Panel Group

After delving into Bootstrap, I encountered an issue. I have a Panel-Group with an image and some text. The challenge is switching the image on hover, but it should change when hovering over the panel, not just the image itself. I've found solutio ...

Looking to transform this PHP function into a jQuery function that generates all the possible combinations of values in an array?

I stumbled upon this PHP code on a programming forum. Here's the original code snippet: function everyCombination($array) { $arrayCount = count($array); $maxCombinations = pow($arrayCount, $arrayCount); $returnArray = array(); $conve ...

Transitioning from Jquery to vanilla JavaScript or transforming Jquery code into pseudo code

Struggling with a snippet of jQuery code here. While I have a good grasp on JavaScript, my knowledge of jQuery is somewhat limited. I am seeking assistance to analyze the following code in order to translate it into plain JavaScript or pseudo code that ca ...

Unveil the content of a string by applying Base64 decoding in AngularJS

After encrypting a token sent from JAVA code to Angular using Base64 encryption, the next step is decryption: String token = "1345BCHCNB"; Cipher ecipher = Cipher.getInstance("AES"); String mykey = "1234567891234567"; SecretKey key = new SecretKey ...

Experiencing Strange Issues with Jquery Image Carousel... Assistance Needed!

I recently created a jquery slideshow using a tutorial I found at this link: While the slideshow is functioning correctly for the most part, there is a strange issue that occurs right at the beginning when displaying the first image. Initially, the first ...

The act of binding is not functioning

Hello everyone, I am excited to be posting on stackoverflow for the first time. Recently, I have started learning ember.js and I am really enjoying it. Currently, I am working on a small project to practice my ember.js skills, but I seem to be having tro ...

Looking to transfer data between files in Nodejs

This is the routes.js file I am working with const express = require('express'), router = express.Router(), loginHandler = require('../handler/loginHandler'), router.get('^/:userId/:userType/:sessId/:lang/:orgId/:merchantI ...

the status of the XMLHttpRequest Object within the realm of jQuery AJAX

When using traditional JavaScript AJAX, we monitor the readystate property to determine the status: 0 - The request is not initialized 1- The request has been set up 2 - The request has been sent 3 - The request is in process 4 - The request is compl ...

Angular - How child components can communicate with their parent components

I'm struggling to understand how to communicate between components and services. :( Even though I've read and tried a lot, some examples work but I still don't grasp why (?). My goal is to have one parent and two child components: dashboa ...

Having trouble with Ajax retrieving the updated JSON file version

I'm pretty new to coding and terminology in general, so I've done my best to simplify my code, although it might still have redundancies. Appreciate your patience in advance. My task involves using an ajax and php script to write data to a file ...