I'm still trying to understand MVC to it's fullest.
I know that in a normal setup, the user requests a webpage. That request gets read by the controller and if for example the user needs to see 5 blogposts, it asks the Model to retrieve 5 blogposts out of the database and give those back to the controller. The controller then sends those 5 blogposts to the View, where they get inserted into a normal webpage. The View then returns the data to the user and they see 5 blogposts on the website. (Please correct me if I am wrong. I find it really hard to grasp, for some reason.)
Now I am using React in a project and I would like to do API calls to my PHP to retrieve data.
Does this mean that if I request "website.com/api/blogposts/5", the Controller in PHP reads that it's an api call, asks the Model for 5 blogposts and sends this data back as a response. This would make React the View, right?
Sorry if this is supposed to be basic information. I just can't wrap my head around it.
It seems like you might be conflating a few concepts so let's take a second to separate them.
Let's talk about web API's first, based on the context you've given you're trying to build a react app that communicates with a PHP API. MVC doesn't necessarily apply here. It exists as a separate application so trying to think of them together in some kind of MVC architecture is going to cause confusion. This API could feature an architecture like REST and would be built to serve data to your client-sided application.
React, my knowledge of the platform isn't extensive however in theory you could map out some type of MVC style architecture in how you structure your project, but React isn't an MVC framework. It's very component based and designed to create reusable components for single page applications. You can read more about this here.
MVC, I find it easiest to explain using asp.net mvc as an example but I'll try to explain a way that doesn't depend on that. MVC is a principle seen most in the typical server-sided web page loading platform. The view being the web page, the controller being a route on a server, and the model defining the data seen on the page which was returned by the server. Most of your MVC guides will explain this pretty thoroughly.
To summarize, if you're trying to learn React for your front-end applications and design an API in PHP to use with it, you'll want to learn React how it was designed to be used. For the API, take a look at good REST practices and just general PHP API designs. If you want to learn MVC, checkout an MVC framework that is built on top of that principle. The concept has some age to it now, so some of the newer technologies like React don't really use the same principles.
Does this mean that if I request "website.com/api/blogposts/5", the Controller in PHP reads that it's an api call, asks the Model for 5 blogposts and sends this data back as a response. This would make React the View, right?
This could be an approach. However, since i've done this before I strongly recomend not to put the API logic inside the controllers. If your application tends to scale, your controller will become huge, and that is something you want to avoid.
What you should probably do is to create a restful implementation that handles the requests and validations, and from there you can call your controllers to retrieve the processed data and then answer the request. With this approach you will get more maintanable and consistent code.
And of course, you will keep your MVC pattern implementation clean and pure.
Related
I want to make a lightening-fast web application and am wondering about the best way to implement it. It's a drawing app that will need support for vector graphics, but it will use a database to store data in user accounts. Here's how I'm breaking it down in MVC terminology:
Controller: Django, hosted on GCP Python app engine
Model: CloudSQL
View: AngularJS
I'm wondering if a Javascript/JQuery approach would be better, since I could have Django handle the database operations and am worried that I'll just be adding overhead with Angular.
I'd welcome any thoughts.
Once you use Javascript framework such as Angular.js and React.js. Your backend and frontend becomes totally isolated. First thing you should do it you gotta make your django REST API. Build your logics to do the vector graphic in your django REST API and build your angular.js app in away that it will "consume" your REST API services.
For the second question, it is depending on your architecture design. If your application is going to be DOM-driven, use jQuery since still jquery still provides lots of UI stuff. However, if it's going to be data-driven and you will use Javascript to organize and display the data in efficient way, choose Angular.js.
Please leave a comment if you have more questions. Thanks!
My project would be a kind of craiglist, a site where users could post anouncements (evereday-life objects, cars, flat etc.). So, authentication, profile page, content creation, display the for-sale objects etc.
I have developed a very large part of the backend: I have a RESTful API in three-tier architecture developed in java. It makes the link with the db, to provide me with different urls and send me the relevant JSON.
URLs example:
http://api.mywebsite.fr/user?userid=1 sends me back:
{"user": {"username": "jdoe1234", "email", "jdoe1234#gmail.com"}}
I have urls for all actions performed on the entire site (anouncement creation, last data updates ... everything, and I've carefully declared them POST, GET, UPDATE, DELETE, etc.). There is also oAuth to protect the API from queries that are not allowed for the token.
That's all for the "server" aspect, I think that there is no problem with that.
But if all the actions are managed by the webservice, I do not see the interest that could bring me a big server-side framework like Symfony/cakePHP, Zend, etc., to make HTTP requests on my different entry points, retrieve JSON and populate the HTML.
So I looked at client framework, like Angular, Ember and so on. At first, it seemed very suitable for my case: possibility of http requests, manage what to do in case of success or error, directly exploit the resulting JSON to populate the view etc.
I didn't even manage to make my choice between angularjs and Ember, both being very similar, but with the release of Angular v2, I fear the maintainability of v1 (if I choose Angular, it will be v1 , because the majority of tutorials and questions relate to Angular 1.X).
I don't know if I'm doing the right thing by choosing client-side framework, I am afraid that they 'brident' (not sure of that word, sorry) me. Plus, it's fully instantiated in the browser, so the user can change absolutely all code and data I provide. That seems weird to me.
I want to be absolutely sure of the technology that I use in case I make this application available to the public for example. I want to do things properly, in order to avoid maintainability or security problems.
Summary: With the things I already have (webservice / api), is it a good idea to use a client framework like Angular or should I stay on big server-side framework like Symfony/Zend etc? Knowing that I position myself in the context in which this platform would be massively used (craiglist comparable traffic).
I'd say - depends whether you want to be more frontend guy or backend guy in future. If you want to be full stack developer then it doesn't apply.
In my opinion, both Symfony/Zend or other big server-side frameworks aren't so exciting as dynamic frontend JavaScript frameworks like Ember/Angular/React.
Also, if you have already RESTful API and OAuth authentication implemented in backend part I'd go with Ember. Why? Ember Data is great tool for talking to backend API. It's mature, it lazily loads records when they're needed and it's very customizable.
it's fully instantiated in the browser,so the user can change
absolutely all code and data I provide...
Ember has built in security like sanitizing data which is rendered in it's templating language - HTMLBars. Also, there's CORS and content security policy (CSP) standard which is implemented in Ember.
I want to be absolutely sure of the technology that I use in case I
make this application available to the public for example. I want to
do things properly, in order to avoid maintainability or security
problems .
In Ember you can create mature, secure, production-ready applications, but you need to comfortable with your Ember skills to some degree to build such ambitious web application, but it's part of building every application.
With the things that i already have(webservice / api), is it a good
idea to use a client framework like Angular?
Yes, it's very popular solution to use MEAN stack or go with Ember + RESTful API.
Why should I choose Ember instead of Angular (which have a larger
community/tutorials/answered questions) ?
Angular has larger community/tutorials/answered questions, but when I started some side project with Angular to learn its possible advantages over Ember, I was surprised how there was no consensus in it's community for doing one thing. So, instead of fast search how to declare and use directives (I think it was the thing that confused me) I have to do another research which way is the best. Also, there are lots of ways to setup project (where to put custom directives, different Angular objects) and you have to do another research which one to choose. I ended up using repo healthy-gulp-angular as my template, but you can see it hasn't been updated for 8 months, but I think during these 8 months Angular had a lot of changes and I'm not sure if this repo is the best choice.
In Ember you have Ember CLI tool which is built with Convention over Configuration principle. You have also Ember Data which utilizes JSON API standard - if you don't have JSON API compliant server side right now, you can write custom adapter to normalize server responses or change how backend replies. In Ember you don't have all that headache and different best solutions to do 1 basic thing depending who you ask.
What means "Single page application" ?
Single-page application is basically a page which doesn't have to reload all assets and HTML when you navigate. It's advantage over PHP - when user moves to another location he downloads only new data for that route. More info here.
Does those frameworks allow me to create real routes ? (
www.myapp/profil/userid etc )
Yes, of course. You don't even need # in your URL. With simple rewrite rule and small amount of logic for profile route and specified path profile/:userid, when user will open URL www.myapp/profile/userid he will be automatically taken to profile route, and userid would be interpreted as route parameter, so you can take this userid and find user record from the store in model hook.
Client = speed, Server = stability
JS frameworks updates once per week
Non-Js back-end once per year
Client side depends to behavior depending on browser
Back is related only on machine but not on environment
I chose FE coz I tired to debug code by writing variables values to database to actually see what is going on in controllers -_-
I've built a REST API backend using Django and am now at the stage of designing a client facing frontend. Though, I can't seem to understand how this client frontend should be structured and which languages it should use.
PHP is server-side, and is usually used as the language for building backends. When coupled with a framework such as Codeigniter, it can also be used to play around with sessions, route URLs, and decide which templates to use. Though, I don't believe it can be used to call my REST API to fetch resources (might be wrong here, correct me please if I am).
Javascript is client facing but is used only once the webpage has been fetched from the server. AngularJS is great, but from what I've read, it seems it only helps add very dynamic functionality into already rendered static pages.
I am really open to any ideas, suggestions, and advice based on your experiences creating client frontends. So, back to my original question, how does one structure a REST client frontend, which language is best for this goal, and if which frameworks should one consider to use?
Update 1
Someone asked whether this client frontend will be run in a browser -- the answer is yes, it will. I am trying to build a Twitter-like web client frontend that interacts with a Twitter-like REST API backend. Basically, everything you see there when you go on Twitter's website.
Since it is a browser frontend I would go with HTML/JavaScript only. No need to use PHP or any server side language IMHO. This has the advantage of being extremely portable.
I would also use a JS framework for that purpose ( the trend nowadays seems to be angular).
REST really, really isn't new. It's been a part of HTTP at least as far back as HTTP 1.1
Have a look at this question: Backbone.js frontend with RESTful Rails backend? the top answer lists 20 possible frameworks for building a front end.
Thanks for your help, everyone. Found exactly what I was looking for here:
http://docs.python-requests.org/en/latest/
A nice little library for Python that allows me to basically make calls to a REST backend from within a Django application, which serves as my frontend.
AngularJS will also be used for to make the static pages that Django returns more dynamic. Why? Because AngularJS by itself can be the complete solution only if your whole site consists of one page. If you have multiple pages where each one has it's own set of dynamic elements, you need a combination of Django and AngularJS.
Apparently REST is still quite new and it seems there aren't many people that have stumbled upon this very fundamental question like I have.
Once again, thanks!
I need to build a single-page JavaScript web app that, on regular intervals, pulls data from a couple of public and maybe a few private APIs, and present & refresh the data in different tables. I could build it purely as front-end code with jQuery and just use AJAX calls, but to keep the keys and everything for the APIs private, I need the logic that retrieves the API data to live in backend code (on the same server).
I'm new to building this kind of application, and wondering how to achieve this with NodeJS. After searching and looking at some tutorials, the only way I can wrap my head around it so far is to have an index.html that displays the view with the empty tables, then on a setInterval, have a local JavaScript function do an AJAX call to a NodeJS (Express) route that handles all the API stuff and returns a JSON object in the response. On success, the local JavaScript can write the results to the html for the various tables/divs.
That sounds OK to me, but since all of this will have to live on the same server, it seems really weird to have a front-end script do manual calls to that same server via a URL/route.
What am I conceptually missing? Do I need to employ a master Express layout and use partials for the divs/tables and have the Node backend process the front-end that way? Or should I stick to building .html and .js outside of Express and maybe use something like Angular to create a more intuitive front-end piece? I'm not sure how either of these scenarios would be put together, I'm just feeling around for a better approach.
Posting as Community Wiki answer, as this got answered in comments:
The way I would approach this is with an Angular app. Exactly as you state you would have an API that is built on nodeJS (a bunch of defined routes that grab data and return JSON), and then your front-end angular app. Correct, every set interval your app would call the endpoints you defined in your API, and then update $scope variables based on the JSON response. Your HTML would actually be updated in real time automatically (since that's how angular works with binding models and templates/partials). I would look into angular - sounds like a perfect solution!
Also, once you understand how the binding of angular works, you will never want to write jQuery html() append() or any of those DOM manipulation functions again.
I want to develop a relatively simple application that calculates some value based on several inputs. I dont want a backend, all the calculation can be done in the browser.
Im a little new to JavaScript and WebApps and I came across Backbone.js.
I really like the MVC design, however, they mention a backend a lot. My question:
Is a backend server absolutely required?
Is a backend server optional but without one there isn't much point in backbone.
Or will backbone will really help me out?
Backend is not required.
Backbone can fully work without any backend if your application doesn't require one.
That depends on your application. If you want to retrieve value of some inputs and calculate a result then Backbone won't do that for you - it will help you structure your code. If you app is simple and don't need support for models, views and collections or routing, then there is no point in using Backbone. Hard to answer this question.
For example: Classic todo example application doesn't use any backend.
Backbone.js implements fetch(), save(), destroy() etc. methods on models automatically performing appropriate AJAX requests and parsing response. So it has a strong support for backend via REST services, but it is optional.
You can still use models, views, routers and events without any server-side code. Just don't call REST methods (or override them at your wish).
You can use localStorage for persistence (you'd have to implement this yourself or find it on the web, like here) but if you don't even need that then you don't need to use any of the persistence methods in backbone.
Backbone is meant to help you structure a medium-large sized application (js-wise), so it doesn't become unmaintainable jQuery spaghetti. With short applications (js-wise) it's really an overkill unless you are trying to learn how backbone works.
Note with js-wise I mean the client side code, if you had a huge backend but the only js would be something that focuses some form, it would not even count as a short application (js-wise).
You can use backbone.js without a backend. However you obviously won't be able to store or retrieve data. Backbone may still be useful for keeping your code organized, however it really shines when you want to separate presentation logic from logic that manipulates your data, which is a goal of the MVC pattern. Generally your data will be stored on and retrieved from a backend.
If you want to play around with data persistence, try out backlift.com. [disclosure, I work on backlift.com] We've tried to make it easy to get a backbone app up-and-running without having to setup a server or deal with compiling templates.