I want to build a REST API using PHP, but without any framework. By the following requirments:
The code should be as simple as possible with OOP development principles in mind, easy to read and expand
Data should be kept in MySQL and to be returned as JSON in the given format
DO NOT use ANY Framework or ANY already written code, but to have structure
User input data validation
There should be no security issues
At first, I thought I should build complete MVC project, but I realized that actually I will probably don't need any views and I will use Services instead of controllers. And also models for both entities (Articles and Users).
I'm still not sure what is the perfect way to do it, so I will just tell you what I`m thinking so far...Sorry if Its a duplicate post but I haven't found much information about this and from the little I found, I got more confused.
I thinking of a simple router.php class that will have a method:
map($httpMethod, $route, $callback)
So, for example, I will call ("POST", "/users/register", registerUser(params)) or ("GET", "/users", registerUser(params)), just like I would do in a MVC web app.
I think I will need a model and a service for each of both entities. The service will execute the SQL for each CRUD operation. I think I know how to create the service, as it won't be much different than a controller.
But I wonder how can I create the model part for both entities. What exactly I will need for the models as a code?
First of all, it would be nice if you agree that this is the right way and if not, I would love to hear a lot of criticism because I'm currently confused and really don't know where to start.
I agree with you.
And suggest you to know about Loopback, it's good, like what you described.
I know your question is how to build your own rest api without framework, but it sounds like you'd actually make good use of at least some components (not necessarily a whole framework), do you really need/want to write a router from beginning?
if so sure, if no maybe some microframework? anyway, symfony has some info on how you would create your own framework (just as an example), they use couple of their own classes (i.e. httpcomponent), but just for the explanation of idea/way how things you want are done.
https://symfony.com/doc/current/create_framework/index.html
I found this library in PHP for get started with REST API's
php-platform/restful
This requires prior knowledge on using Composer
Related
Good morning,
I am attempting to setup some test using Silex\WebTestCase to ensure that my application is working properly. In order to do that I need to load up some referential data into the backend storage. I am using ElasticSearch with the https://github.com/doctrine/search library.
I thought that the best way to do this was with Fixtures, namely symfony/data-fixtures. However I am unable to work out how to use them. This is because the fixtures need to implement the FixturesInterface that states the load() method should recieve a compatible Doctrine ObjectManager, however as I am using the Search library I do not think I have such an object.
As this is for test data then I could write something that is home grown but I would like to use things that are appropriate and written for this scenario.
Does anyone have an examples of using fixtures in a Silex application that I could at least look at to point me in the correct direction?
Thanks, Russell
What I'm looking for is a way to remove the model from a set of PHP files that make up a website. It's difficult (for me) to explain.
By models I mean models in an MVC sense.
As an example say I have this website:
index.php
about.php
shop.php
checkout.php
All of the above PHP files use the same database. I have separated the views by adding templates using a view.php file that renders the correct template with values passed to it.
I am not looking to use a framework that's already out there. I'm looking at writing my own in some senses, with only the bits I need to use in it.
If anyone would like to explain why this is not necessary, or a better way of doing things, then I'm open to that too.
Thanks in advance.
Writing you own MVC framework will take time, but you will learn a lot in the process. So, if you have the time/resources to do it I definitely encourage you to do so.
In this context here are some small pieces of advise that may help you:
Create your domain model first. I'm assuming that you are going in the OO way, so think about your domain problem and create the abstractions that best represent your problem. Try to keep it decoupled from cross-cutting concerns, like persistence.
Test a lot, test often. Try to test (and run your tests) as you create your domain model. This will be specially valuable when in 6 months you add a new feature and want to make sure that you haven't break anything. If you can separate your domain model from anything external (like the persistence layer or third party web services) the testing it is going to be a lot simpler. Today PHPUnit is pretty much the de-facto standard for unit testing in PHP.
You don't have to write everything from scratch. There are a lot of libraries that can help you to ease the development of an MVC framework, so that you can concentrate on what you really want to develop. For example, you could use Slim to handle the page routing or you could delegate the persistence stuff to Doctrine 2.
It is always nice to analyze how other frameworks solve things. You may want to look at products like Symfony or Kohana or even check how Elgg handles its views system. Also, if you want to check out something radically different you can take a look at Seaside's architecture.
Coming back to your original question, for me the key is to keep things from different layers as decoupled as possible. While I have only used the version 1, Doctrine 2 seems like a good candidate for persistence, since it allows you to create a domain model that is quite independent from the DB. This is a huge step. The second thing is how handle the view system. This is quite developer-taste dependent. For example, I like to model everything with objects, so I like Seaside's approach. On the other hand, Elgg's way of handling views is quite nice and maybe fits better with the way things are handled in PHP. Here is when you may benefit on doing some research before deciding on a route to go.
HTH
As someone who has written his own PHP framework, and with the same sensibility as yours, I can tell you that using a framework is a fine thing to do. That said, start by writing your own - you'll gain greater appreciation for the true structure and utility of a framework.
You'll want to learn about the Singleton object pattern. It is a major differentiator in the kinds of objects you can develop in your framework.
When you have written a few models that your files/controllers (presuming MVC) include, you will begin to see where to abstract a 'base mode' from which others extend (hint: the DB singleton).
When you start pulling in configs and the like, then you'll have your first framework object from which all other bases do their extension.
i have a project i took over. it is an app that has been build over many years with PHP and mysql.
It currently has a sort of good folder structure but the code itself is very poor written.
There is php, sql statements and html code in almost every file.
There is javascript code generated using php echo for not reason and so on.
I will like to use for further development either CakePHP or CodeIgniter, even if that means that for the new features some code will be written that already exists (eg.: maybe utility functions) in the old code.
is it possible to integrate one of these frameworks into an existing app?
which one is easier?
do you have any links on how to do it?
thanks.
I have very little experience with CakePHP so my answer is going to be about CodeIgniter. I played with CakePHP for about a day and that was almost two years ago. In my opinion it will probably be easier to integrate with CodeIgniter although someone more experienced with CakePHP might prove me wrong.
Here is the approach I would take. I have never done this, but it seems like a logical way to approach the problem. I suppose this approach would also work with CakePHP.
First, start with a fresh CodeIgniter install using the latest version.
Next, create controllers and actions (controller methods) that mirror the current structure of the application. For example, if you had a page with the URL http://example.com/users/view you would create a Users controller with a view() method.
Next, create view files for each of the current files of the application and load them via the appropriate controller methods. The goal here is to get the application working using CodeIgniter's routing system although at this point you won't be utilizing any models, libraries, or helpers.
Once you have the application sitting on top of CodeIgniter, start refactoring it to fit into the MVC pattern. Pull out application logic (queries, form handling, etc...) from the view files and place them into the controllers. Keep all presentation logic and HTML in the views.
Next, refactor the controllers. This is where it gets tricky because controller code can be placed into models, libraries, or other controller methods. A good starting point would be to take all of the queries and put them into appropriate models. Compare your controllers and see if there is any code duplication. That is a good sign that you should remove it from the controller and place it elsewhere. Unfortunately I can't really tell you where because it differs in each situation.
Continue refactoring your application until you have it in a workable state that you are pleased with...
Hopefully this helps. I certainly missed some critical steps such as setting up and configuring CodeIgniter but if you're serious about doing this I would highly recommend reading through the CodeIgniter User Guide to get a good idea about how it works. You should also get familiar with MVC (model-view-controller) if you aren't already.
There's not really a one size fits all solution here but hopefully I've given you some ideas or at least a starting point to jump off of. If you have any questions or are a little confused drop a comment below and I'll get back to you.
In my opinion, it's easier just to write your controllers in CodeIgniter (I've never used CakePHP) and models, than you just copy paste with some adjustments the views.
I used to develop websites using php . I like to learn some framework using php.
So I like to know how effective MVC is ?
Is this easy to learn ?
MVC is a way of organizing code that seems uniquely well suited for web applications. You'll have to organize your code in some particular way, try MVC and see if you like it. It's also the de-facto standard in web app design, so it makes your code easier to understand for other programmers.
It helps me minimize mixing languages -- views contain all the HTML, models all the SQL, and controllers describe and handle the API and support code (like authentication).
I have to say that when I first tried to get my head around MVC I had a great deal of difficulty (especially being someone who is self-taught and started with PHP). Put most simply, and most valuably for me, MVC is a good way to organize your code. It provides a template for separating the different layers of your application, which again sounds confusing, but actually isn't. (Again, this is meant to be an explanation of why MVC is useful and how to get started with it, not how it functions ... which I don't totally understand.)
First off, one really simple way to think about it is to compare it Wordpress (this is assuming you've played with Wordpress). Views function in much the same way as "themes": They are a simple way to combine presentation markup with whatever data is being pushed out to the page.
Models describe (and can interact with) the database.
Controllers do everything in between. (Calling functions in models, loading data into views.)
But it's also important to note that you can use MVC in any way you want to. While the idea is to get you to use a specific organizing pattern, no one is going to stop you from doing it in whatever way works best. I know quite a few folks who forgo models altogether and just use Controllers/Views to do everything they need. I found CodeIgniter to be pretty easy to get up to speed on, and now that I've got the hang of it I find it incredibly useful for both the functions the framework provides, but more importantly, the organizing that MVC forces me in to.
Hope that's helpful.
MVC is a very good design pattern for developing applications. It allows you clear separation between the views, the data access and processing logic which will result into more maintainable code.
Obviously learning MVC is going to be different for each person. My recommendations would be to read everything you can on MVC/PHP-MVC/PHP OOP that you can and then try to write your own framework. Then rewrite it using the things you learned the first time. Repeat.
Few of the major PHP frameworks implement MVC. Most use some variant of "Passive-MVC" or "Model-View-Presenter". They're following the concept, not the actual MVC pattern (which is a runtime organization for graphical apps, not for generating page output).
That's not to say the PHP interpretation of the concept doesn't bring any benefits. It's commonly believed to provide a better structure for large or growing web apps. It's less useful for implementing simple tasks.
I guess everything that was to be said about MVC was said already... so I'd like to point you to a good PHP framework to start with, should you decide to go with MVC - CodeIgniter. It's probably the easiest one to start with if you never used MVC before.
Just to add to all the wonderful answers given about MVCs, an MVC framework will do all the basic work for you and it helps save time. You'd be working on things custom to a particular project like its business logic intead of the basic Create, Read, Update and Delete functions.
#gowri
You can try with any php frame work. You are at initial stage so start learning codignator or cakephp. Both have good documentation and support. I recommend you codignator. Easy and good mvc.
I am trying to create simple php framework .But i am not sure about class structure for example which classes should extend to which classes .Firsly i am know that some basic classes such as Router , View classes have to access some basic data such as requested url or requested ccontroller and action so how can i import basic data to these classes .If my question is not clear please explain your own experiances and ideas about frameworks.or if you know please talk about known framewoks such as zend , cakephp or symfony
There is no best class structure. Depends on what you are trying to do. Do you mean purest MVC design? Most testable? Most easy to understand?
There is a simple rule of thumb:
Either you have a need that the standard frameworks can not fulfill
or you should use a good standard framework that does what you need.
In the first case the restriction will be the driving aspect in your design.
There are no general design rule for class structures in frameworks. But try to keep this in mind, if you decide to write your own one:
Minimize dependencies between modules
Always try to give default values
Try to minimize the overhead
Talk a lot with peers about it to find flaws early.
If you've never worked in someone else's framework you will have no idea what ideas work for you and what don't. If you've only ever worked with dis-organised spaghetti code, then you will have some idea of what makes sense for you. If you've made substantial re-organisation to dis-organised spaghetti code in more than one unrelated project, you should have a good idea of how you think in building a framework. :-)
If you don't have a firm idea of how you want to write a framework, but you want to write one, I think you need to start with nothing and build it organically. However, you should have some idea how you want it to look like, even if it's something as silly as where you want the include files to live. In other words, all you need is a starting point. Then it's a matter of re-factoring ugliness as you encounter it. Before long, you will have a database handler, a dispatch mechanism, perhaps a data access layer, just maybe even a templating system!
Responding to #MrFox, though, you should be aware of dangerous dependancies. Obviously a data access layer will depend on a database handler; so what you don't want is for your database handler to depend on your data access layer. In fact, you don't want them to have intimate knowledge of each other, either. It should be a reasonably "black-box" interface.
Also, a number of frameworks try to build "one" object heirarchy. This means they think an Action is-a Model is-a Database Handler. I personally have problems with this mis-applied abstraction, so this is a heads-up to not be afraid to spurn this idea if it doesn't work for you, either. As #Tyndall said, there's no one, single "right" way to do it.