How to integrate php (Phalcon) and Vue.js components?


Have you been looking around the internet trying to find a good way to integrate these two frameworks? Banging your head against the wall, figuring how to make them work in harmony? Are you to a point, frustrated and almost giving up?        

 Both frameworks are very powerful, yet there is very little documentation or information on how to integrate them seamlessly. One being a server-side framework (php Phalcon), whereas the other a frontend framework (vue.js). Individually each of these frameworks are very powerful, yet combining their power will make your application so much more remarkable, much easier to maintain and to be honest, giving you a much greater joy to program.

We will touch on, how to design and structure code in phalcon, how should data be passed between phalcon and vue, how should your vue components be designed, how should you design your views in the phalcon MVC and what is the best way to structure your code. Highly recommend reading this article from start to finish as it touches on some fundamental concepts. Every idea thus, is built on these core principles.  

This article is for intermediate to advanced users, but even a novice user will gain a lot from it. Though this article is written with Phalcon PHP and Vue.js in mind, the underlining principles apply to any server-side code and any frontend framework. This article is more on theory. If you want just pure code examples, please check this article out.

On the other hand, this article is not a how-to-guide on how to install, use or learn phalconphp or Vue.js. We will touch on how they work and give examples. For an indept knowledge on these frameworks please read the official documentation. For that matter, a basic understanding of how server code works, how javascript and the internet works can help you gain a lot more from this article. Also, we will not be comparing different frameworks. We have chosen to explain phalcon php and vue.js as both these frameworks are used extensively in building software at ANTSAND. 

So, what is the best way to integrate Phalcon + Vue.js?  

Before we delve deep into the integration, we 1st must understand the strength and weakness of these frameworks. Further, we need to understand what is PHP, what is javascript and how they work. 

Php Phalcon is a MVC (model view controller) written in C and complied as a php extension, to help php programmers write modular code. PHP itself only runs on the server. Fundamentally this is what php or any server-side code does. 



The web browser cannot interpret php code or any server-side code.

On the other hand, vue.js is a javascript library. Javascript is a programming language that web-browsers understand. Its main feature is to manipulate DOM (document object model) to add interactivity to the website. Vue.js is a framework written in javascript, to help modularize javascript code. If your application is small and you need little interactivity, vue.js can be an overkill. On the other hand, if you have 1000’s of lines of javascript code and finding it hard to maintain your code base, using a framework is quite essential. 

The web browser mostly interpret 3 languages to display content visually. CSS, javascript and HTML. This shows that to display any dynamic data (interaction with database), the server code must do all the processing, convert to HTML and then send the information to the browser. It is important to note that at the end, every php code is converted to HTML by the php engine.

Note: A web-browser can also interpret data objects or other markup languages like JSON and XML. The browser for the most part receives these objects using API's through AJAX calls. These objects are then interpreted by javascript which renders the data to the DOM. For more on these objects check out the next article -  Using restful API between php and vue components

To integrate php with any javascript framework, this is how the process is:

PHP ------> PHP Engine -----------------------------> HTML

*.Vue ----> Vue engine(webpack/broserify) ------> Javascript 

*.scss -----> Sass Engine (webpack/gulp/grunt) --> CSS



The outputs of all these engines can now be understood by the browser. 

The goal when integrating php and javascript is to make sure the html generated by php,  javascript generated by vue work in synergy. Javascript’s main goal is to manipulate DOM objects, and HTML’s content is nothing but DOM objects. The code generated by php must have elements or DOM objects that javascript (generated by vue) can control. This is fundamental to making these frameworks work.   

We can tell php to generate particular HTML tags for it to be further controlled by javascript. For e.g. we can echo in HTML "let-vue-fill-this-tag". In the *vue component file, we ask Vue to search for this tag, and if it finds it, manipulate it accordingly.  
*.Vue -> javascript -> look for “let-vue-fill-this-tag” in the html file. If found, we can now manipulate this tag. If not found, do nothing.  

 

Understanding how php and javascript work under the hood is part of the equation. The next question to answer is, how should you structure your code?

To explain this, we need to understand how the server and php work together. 

The server is a software program running on a computer trying to listen and server specific requests. When you type antsand.com on the webbrowser, the browser communicates with a DNS server, translates Antsand.com to an ip/ipv6 address, obtains the ip/ipv6-address, packages a set of information into packets and sends that information to a computer with that specific address over a bunch of routers. The computer with that ip/ipv6-address is where the code for Antsand.com resides. When this computer receives this information, it looks at the packet and checks for programs in the computer that can handle this request. Since the packet that was created by the web-browser is a tcp packet on port 80 or 443, a webserver is listening for any request on those ports. Port 80 and 443 are standards ports for websites. Once, the webserver deciphers the packets, it then looks for what information the browser is requesting. If the page that the browser is requesting needs to be serviced by a 3rd party server, the web-server will send that information to such a server. In this case the 3rd party server is the php engine.

Webbrowser -> router -> Computer(Antsand.com) -> webserver (nginx) -> search for *.php files -> if found send to -> php server (php-fpm) 

Webbrowser (html) <- router <- Computer(Antsand.com) <-webserver <- html file <--- php server(php-fpm) 

Webbrowsers -> scans html -> request more information defined in html -> CSS/images/javascript 

The above steps are repeated till all the information defined in HTML is properly loaded in the webbrowser.



What this implies is that the html generated by php might need additional interactivity through javascript. This is what you have in control. What parts of the html you want php to generate and what parts of the html you want javascript to take control.    

What is important in the above explanation is that the web-server communicates with php-fpm to generate html from *.php files in real time, wheras the server treats javascript as a file and does not communicate with any 3rd party server to generate javascript files in real time. The javascript files must already exist as a file. With the introduction of node.js and modern servers, this may not be the complete case, but for the sake of this argument and for most production use cases, javascript is not produced in real time. Therefore *. Vue component files must already be converted to .js files when php’s html references the javascript file.

When designing a webpage, you need to know what parts of the html should be generated by php and what parts of the webpage you want javascript to load through AJAX. Once this is defined the rest is just planning and execution.

 There are various ways to do so, but this is how we at ANTSAND approach this problem. The main logic of your application is written in server-side code. Your server-side code has all the information on how each page of your website must load, what content to display, how your website is to be navigated and how each webpage of your website flows with respect to the other. It contains the core logic of how your website should be navigated. As a result, javascript must sit on top of each rendered page. 

Php Phalcon being an MVC, this is how the code structure at ANTSAND looks like:
Module -> (Model, View, Controller, Vue)


Each module in Antsand code structure has a Vue folder. This is where all the *.vue files are located. We want to keep all the vue components related to this php module under one directory. The output of the vue component is then generated to the public folder structure where the web-server can find the file. The javascript file is generated based on the *Vue components. We don’t need to touch the generated file. All we need to make sure is where the file will be generated and if the web-server can find it.

A deep dive into how php-phalcon works or for that matter any MVC.
A MVC is a Model View Controller. Generally, the Models folder contains files that interact with the database and contains core server logic. The Controller folder contains files that help is designing how you want users to navigate through your application and what content you want different users to see. The View folder contains files that tell php how you want HTML to be literally generated. In Phalcon, if integrating the volt engine, your view folder would then have volt files, that are converted to php by the volt engine which is then used to generate HTML files. 

Why is this important?  
Understanding how MVC works will give a much clear understanding of how you want your code to be structured and how you can make both these frameworks work together. When HTML code is populated through the javascript framework, in this case vue, you want to know how vue is going to populate the content. Vue would be using AJAX calls, which would be calling phalcons-php code and asking it for specific information which it can then render under a specific html tag. Let me give an example.

This below picture is the antsand blogging dashboard
We have 3 different components to it.These three tags are defined in php and echoed as HTML tags. After the browser loads this HTML page with these empty tags, we want those tags to be populated by javascript.  Therefore we have divided our vue application into components.
a. Profile information
b. The blog navigation panel
c. The editor space


The visual display for each of these components is written in *.vue files. 
The data that needs to populate this content has to come from a database. Javascript written using *.vue components makes AJAX calls which calls php-phalcon, phalcon does all the processing, assembles the data as a JSON object and sends the information. Javascript receives this information and displays the content of the JSON file in a visually elegant way.  

Just as how we want our front end to be divided into different components, we need to have different controller actions in phalcon that explicitly help in providing the relevant data to each of these vue components. This way, we know that each controller action in phalcon has a specific purpose and is tightly coupled with interacting with vue components for the data requested. 

When designing your application, you need to think,

*.vue component -> makes a (ajax request) -> request data from a particular link -> phalcon reads the link, forwards the information to the necessary controller and action -> fetches data from the database -> echo's the result in a JSON string/object. Vue read this string and display the content accordingly. This is the lifecyle between a vue component and php-phalcon.

The below image represents a visual workflow. 


Next, How does vue.js work? What are vue.js components and how do they work in vue.js?

Now comes the big question. How does it work. Vue.js is not another jquery like framework. You can technically use both jquery and vue together as they both serve different purpose in writing javascript code. Just as how php-phalcon is a MVC framework to write  modular php code, Vue.js is a framework to write modular javascript code. It's main purpose is to separate different elements of a webpage into components. Each component can then render elements of a page accordingly. This help maintain your codebase. It also helps in scaling your javascript application. *Vue files are vue component files that have information on how to render that particular component. It has the logic of where in the HTML file this component needs to fit. Accordingly you can write a template and add logic to that template using javascript. The vue engine will then take all the vue files and compile them into one big javascript file. You can control how you want the javascript file to be rendered. You can even have each component have its own javascript file. Depending on your application, you need to make the judgement.    

Now that all the concepts are explained, in the next article I will give a live example. We will create a simple application where we can render a simple "hello World" page, integrating phalcon and *vue components. 

I hope you found the information in this article worthwhile. If you have any questions, or feel some of the information might be incorrect, please comment below. I will be glad to hear your comments. The most valuable comment that I receive, I will send my personal folder structure with all the files and necessary information on implementing these two frameworks. Do COMMENT BELOW. 



Conclusion:  

Please comment below if you have questions, ideas or how you can apply it. At ANTSAND, we apply everything we preach and teach. What we put out is based on our experience, our failures and success. We love to be transparent, as it really brings out the best in us. 

We will soon be creating a $5 monthly marketing package for our readers. You can pay us for one cup of coffee every month, and in turn we give you strategies, ideas, tactics, mindsets and exercises, you can apply in your business immediately. If you want to know more about it, just type in the comments below, "Coffee with ANTSAND". We would love to hear your feedback.

If you want to read other blogs that might interest you, have a look below.


More Stuff from ANTSAND

Business, UI and UX:

If you are a programmer, you can read more on our Programming blogs:

Life style:


Written by Anthony Shivakumar
Founder, Lead Marketing and Software Developer at ANTSAND

Anthony has a Master Degree in Electrical and Computer Engineering. He has worked in major software firms for the past 15 years and currently runs his own software and marketing company.

He continues to write articles related to marketing, programming, sales and growth hacking.

10 Comments

MannyF
Dec 05, 2019 External
Hi Anthony,

Your posting here great.

I am an old folk, but young at heart accountant, used to develop clipper/dBase III then PHP 4 some time ago. Now I am going back to development hoping to continue my "on hold" project for a cloud accounting whose feature I have not seen when I supported Oracle and Nav Vision, and I played with SAP and used mostly in my accounting career Quickbooks and Xero, but still, the features I envisioned for a modern digital accounting system are not in those software. So, now that I am planning for my retirement in the next 10 years, I am trying to study back PHP and Perhaps using Phalcon or I can make my own PHP MVC with Zephir-Lang.

I greatly appreciate your post as it gives me the enhanced views of what I already know.

Cheers,
Manny
Boyong
Aug 28, 2018 External
Thank you very much. Keep it up.
Anthony Shivakumar
May 10, 2018
Hi Guilherme,

Thanks for your comments. I personally have not tested using Vue server yet, hence I really cant comment. This is something I will be investigating more in the future. I do have a few questions regarding this design though: (this reply is more like a memory dump of questions I have 😊)
1. If you use vue server to render the full html on the server side, then what is the need for php?
2. Can vue server talk to any database like mysql or mongodb? Yes. I know mongodb and mysql has a npm wrapper, so technically vue can take advantage of it.
3. In what case would it be necessary to use vue and php as the backend server language? Wont it be complicating the design? The basic flow would be
a. Compile *vue files to html using webpack
b. Insert compiled vue html into Phalcon volt or .phtml file
c. Phalcon renders and outputs to the server the full content
Few things to think about in the above process: can phalcon now manipulate the html generated by vue? Would it need to? I guess depending on the design.
What roles does Phalcon play, if everything is rendered by vue? I guess controlling the high level MVC design and control flow/ user flow of the website.
If vue and Phalcon volt are tightly coupled, what issues with code maintenance can there be? If vue html is just piggy backing on volt to eventually render html to the browser with no additional interactivity between the two, then it seems quite scalable.
If we had to make volt interact with vue's html, what would be the best way for them to communicate? Hardcoding syntax like [ volt will manipulate this ] would be a bad design. Rather, if we can make the two interact with common objects like JSON or xml, it can be very scalable.

Let me look more into this approach and get back to you. If you are willing to share more of your thought process, that would be great.

I spent lots of time thinking about how to deal with phalcon and vue. I couldn't think yeat in solution to deal with some cases which I don't want to create another request to get information about the user, I'd like to load the page with the content generated or the content be generated on server (like Vue Server).

Well,

In the whole project one file .phtml or .volt which contains the headers, scripts (generated by webpack), css files.

I use vue-router to organize the routes and load async the pages. If I need to get some data on the server it'll be required to make a request to get this data. I split my js scripts with the plugin CommonChuncks and for production I add the hash into files name to avoid problems with cache and I use HtmlWebpackPlugin to write these .volt or .phtml files with the files generates by webpack



Anthony Shivakumar
Mar 26, 2018
Yes, Phalcon is very customizable. It also depends on how you use vue. There are various ways to use vue as a frontend framework. Sometimes using vue as components is an overkill. You might just need a common vue file for simple dom manipulation in your application. In that case, separating frontend and backend is a good idea.

If you use components, and if your components are directly coupled with your php-phalcon volt files, it is a safe idea to put then in the same folder. Reason being, both phalcon volt and vue.js are rendering the same HTML page. As your application grows, you can get very confused which vue component is linked with which phalcon volt.

Regarding multi module, yes I do configure multi-modules in many of my application. Truth be told, I have rarely used php-phalcon micro app. In the next sequence of articles I will be writing more on multi-module configuration with phalcon.

Diplo
Mar 25, 2018 External
Hi Anthony,

Thanks for sharing your approach. I have a similar comment to Todor: Phalcon makes transparent the difference between frontend and backend, so why adding vue files in the backend. Furthermore, do you use Phalcon multi-module MVC in your apps or when you say that they server as API, do you prefer to create Phalcon Micro for integrating it with Vue?

Cheers!
Anthony Shivakumar
Mar 21, 2018
Hi Todor,

Thanks for your feedback. Appreciate it. This is a sequence of articles I am going to write on this subject.t In my next article which will be published on Friday, I will give a lot of code examples. This article is more for people who don’t want code examples but want to understand how things work.

Getting back to your question.
I have a few comments based on your approach

“By the way the way I integrate frontend frameworks with phalcon is putting the whole frontend infrastructure (webpack, vue, etc) in the public folder of phalcon and then in IndexController.php > indexAction function loading the index.html file which is produced by the frontend framework”

A rule of thumb when I design applications, I try to keep everything related to an application in one folder. I don’t want to change my folder structure based on the programming language. As a result, this is how I structure my code:

Rootfolder
 App
o Modules
 Controller
 Views
• Index
o Index.volt
 Fetch javascript from public/javascript/vue.js (generated file)
 Vue (*.vue files)
• Main.js
• Abc.vue
• Xyz.vue
 Models
 Sass
 Module.php
 Public
o Javascript
 Vue.js (generated file)
 Package.json
 Node_modules
 Webpack.config.js

I think tell webpack, that look into the modules folder and search for the vue folder and find the main.js file. Compile the output to the public folder. Then I tell index.volt to find the generated file.

I keep this structure as when the project expands, you don’t want to get confused which vue folder links to which phalcon module or controller. By keeping all the files related to a module in one folder, it helps to maintain your code better.

. In other words the index controller loads the frontend framework and all the other controllers serve as API.”

Yes. This is the right approach in my opinion.

IN my next article I will be giving a lot of examples on this. At the end it also depends on the project scope.

Thanks,
Anthony

Todor Pavlov
Mar 21, 2018 External
This article was not helpful at all - the only place in it where you say something about the integration of vue and phalcon was the title...
Still it is an art to be able to say a lot without saying anything.
You had to start directly with the implementation article - let's hope that it will be better than this one.
By the way the way I integrate frontend frameworks with phalcon is putting the whole frontend infrastructure (webpack, vue, etc) in the public folder of phalcon and then in IndexController.php > indexAction function loading the index.html file which is produced by the frontend framework. In other words the index controller loads the frontend framework and all the other controllers serve as API.
Anthony Shivakumar
Mar 16, 2018
Hi Gabriele,

Thanks for your comment. I am currently In the process of writing the 2nd part. In terms of examples, do you have any particular suggestions?
If you have a list of things that is frustrating you in the integration, let me know. This way, I will be able to present examples that solve your pain points.

You may have questions such as:
Who converts *.vue files into javascript? Do we use browserify or gulp or webpack, and how do they work? I can present code examples on that
Or, how does vue components really work? How do we organize the html file to have vue components? I will demonstrate a lot on that too.
Or, how does each component interact with Phalcon? How should data be passed between the two frameworks?
If phalcons volt uses {% %} tags and if vue too uses {% %} as the same delimiter. HOW THE HECK DO THEY WORK TOGETHER??
How should you structure your code? What is the best practice way of structuring and maintaining Phalcon and vue?

Let me know what you are specifically looking for.

In my next article, I will give demonstration on a very simple ecommerce website, and answer the above questions using a live code example. The article should be up by next Friday.

Thanks,
Anthony

gabriele
Mar 16, 2018 External
Hi Anthony,

how much time I have to wait for your live example?
I'm looking forward to read it.

thanks,
Gabriele

Leave a Reply

Make sure you fill in all mandatory fields.Required fields are marked *