Adding Front-end framework to existing PHP project
Daniel P 🇨🇦
Posted on July 21, 2019
This was an answer to question at stack overflow that I couldn't post because it was closed before I could post it. https://stackoverflow.com/questions/57129851/how-to-use-js-frameworks-like-react-and-vue-and-es6-with-a-php-project
For a newcomer to front-end frameworks, I'd say probably the easiest way is to make small incremental changes replacing jQuery with Vue. I'd say Vue, and NOT React, because of the learning curve and changes since v. 16 that make it less friendly for un-compiled use. The React team seems to have dropped interest in supporting this kind of progressive approach by deprecating React.createClass
from the main package. You can still do it, but it's an extra package now.
You can add incremental chages by adding a new script tag like
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
into your PHP template which will load Vue in addition to jQuery until you have removed jQuery completely)
Then find a component you want to convert from jQuery to Vue.
You can now add a Vue template or component into your PHP layout/page and the JS script into the page, a page script file, or a component-specific script file.
Rinse and repeat for other components.
It's important to note though that this is not the best practice. Ideally you'd have a JS pipeline that generates a SPA(Single Page App) and deals with APIs from your PHP app. This is my preferred way of developing apps, but it's not a must. Doing it the way I described will add some pain when it comes to managing the app long-term, but it's likely not as bad as managing jQuery. As long as you organize your files well, using this method is a reasonable way to get started with adding some advanced functionality. If you know you're going to support modern browsers only, you can start defining templates in the script using template literals, which will help with code management, since you can keep your vue layouts in js files instead of in php templates. Later on, as you get more comfortable, you can start consolidating the project into a unified SPA that gets all the benefits of a compiled project.
Posted on July 21, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.