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.
Related
I'm currently creating a webpage and I have a problem, which I couldn't find answer for. I'm using Laravel framework and I need to store pages somehow. I would normally use MySQL or SQLite or some other DB engine like that, but some of the pages I write contain PHP code.
Specifically, page /app downloads something from somewhere using file_get_contents, does magic with converting encoding and displays the downloaded content. Page / is just plain Html.
I thought about using eval() but it seems like an extreme overkill and insecurity to me. Also I would like to leverage the MVC somehow in this by having the logic of /app in controller and the text of the page in some DB. So I need to find some type of model which would allow me to this.
I'm using the "function-per-page" approach.
i.e.
Class MainController extends BaseController {
public function getIndex() { // some code }
public function getApp() { // some code }
public function getDocs() { // some code }
}
etc...
Any ideas on how to deal with it?
EDIT:
A little bit of background. I'm not a newbie, it is just that I don't know how to deal with this project. I have experience in writing projects like blogs using Laravel.
The page I'm creating is "portfolio-type"; mostly static, but 2 pages contains scripts as stated above.
Also I already have working version, but I'm rewriting it from scratch. Original version used Slim framework and pages were stored as php files, then included to template based on url.
include "pages/$url_part.inc.php";
As this SO Answer states, there is no way besides eval to execute php code that resides in a database.
My suggestion would be to try and learn a bit about laravel and MVC and to redesign the application afterwards. A resource I can not recommend enough for learning laravel is Laracasts. Laracasts also provides a very well done series called Laravel from Scratch. But chances are good you already know that.
To address your issue once more: I think it is worth thinking about a redesign of the whole app. Since the workflow with laravel is super fast, this is better done sooner than later, because your design will lead to more problems in the future, because it simply does't fit well with laravel. Also, this will open up a lot of nice possibilities, because you can use the full power of laravel.
The Database is what lies behind models, the M in MVC. Only actual Data should be stored there, no Logic (C - Controller) or Presentation (V - View).
If it is just a normal website (like a Blog or sth.), think about not developing it all by yourself. There are great free Content-Management-Systems on the Market (like Wordpress, to name a very popular one), which also offer a lot of possibilities for extension and customization.
Given the little information you gave, this is the only advice I can give so far. I hope this helps a litte, and sorry if this stuff is to basic for your level of knowledge, but it is hard to tell how proficient the OP is in many cases.
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 almost completed a PHP project, using MVC, jQuery and Ajax. It is pure PHP project. I don't use any frameworks in the code right know. I would like to change that.
Doing some research, I found, that Yii turns out to be one of the best frameworks out there.
Is it possible to somehow migrate pure PHP project to Yii?
If so, then how to do this? Which steps should I follow in order to reduce the workload and enjoy the benefits the Yii framework presents?
I'm a total Yii newbie, any insights appreciated.
TL;DR : Don't do it. It's a really horrible idea.
The Rant ..
"Framework" is not a magic sauce, that you add to a project, to make it better and shinier.
Doing some research i found Yii turns out to be one of the best frameworks out there.
What a strange research you have done .. I would love to see the materials. Especially, since I would rank it as 3rd worst PHP framework. Only surpassed in it's awfulness by CodeIgniter and CakePHP.
And the reason for it is the extremely bad quality of code, that this framework displays, combined with the bad practices, that it perpetuates.
Why avoid migration?
From your description is obvious, that you are NOT familiar with this framework and have no previous experience with it.
In management of projects there a subject: risk management. And in this case, adding a previously unused framework in final stages of project would constitute a high probability an high impact risk which also, due to the sage of project, is completely unmitigated.
It means that there is a really good chance that something will go wrong. And when it does, it most likely will sink the project. Or at least push back the release data by significant length of time.
In a perfect world frameworks are used to simplify the repetitive tasks of development, at the cost of some performance. Those are the tasks you do at the start of the project. You are not at the start of a project. This means that you will gain no benefits from this "maneuver".
Why not Yii?
As I noted before, there are also reasons not only for avoiding adding framework to an existing project, but also reasons why to avoid Yii in particular.
The inheritance nightmare
All your controller will extend class CController, which extends CBaseController, which extends CComponent
All your "models" will extend ether CActiveRecord or CFormModel, which extends CModel, which extends CComponent.
Both of there chains contain static variables and execute static methods on multitude of different other classes. Combination of these factors will make debugging extremely difficult and tedious.
Global state
There are several forms of global state. One that people in PHP usually know are global variables. But that is not the only form. Every time you have a class that contains a static variable, it also creates a global state, that can (and almost always - will) cause seemingly unrelated instance mysteriously interact.
Use of global state is a core mechanic. You will see static calls all over the codebase, and the Yii's configuration file would not function without global state.
And every time you call Yii::app() you are accessing and/or changing it.
This makes unittesting impossible for Yii applications. And debugging turns into exercise of using grep on your whole project.
Tight coupling
When you create an application in Yii. It becomes bound to it. You cannot execute parts of your application without launching the full framework. Mostly it is due to the static call, that you end up adding to your code.
Every time you add a static call in your own code, that piece of code becomes tied to the name of the class. That essentially is tight coupling.
As you might have noticed (hopefully), there is another way how to achieve the same effect - the use of new operator. That is another way of coupling some code of yours to a specific name of a class.
No interfaces .. none .. whatsoever
No matter how horrible the configuration of a Yii project is, the configuration file was a well intended gesture. The least harmful way to introduce external code and replace existing components in so messed up codebase.
But unfortunately it brings in the focus the problems caused by lack of interfaces and the existing coupling.
One of the component that developers will try to replace is the CUrlManager. Mostly due to way how you can pass additional parameters.
An interface in OOP specifies the contract between two instances. It lets you define the capabilities of an instance, the methods that can be used by others. When it's not there, in a large codebase, you are left guessing, which methods are required and which are not.
In case of Yii components the problem is compounded even further due to static call and deep inheritance. The above mentioned CUrlManager extends CApplicationComponent, which extends CComponent. Also the same file defines CUrlRule and CBaseUrlRule classes.
When you are writing a replacement, you have to write some code, plug it in the configuration and then test it by running your applications. That way you know which method (or parameter) next you need to add.
Basically, it's the "save-an-see-what-blows-up" method of development.
That's not MVC!
Yii does not implement MVC or any of MVC-inspired design patterns. What it calls "MVC" could be described as ActiveRecord-Template-Logic pattern.
Instead of having proper model layer (yes, it should be a layer), the creator(s) of Yii opted for collection of active record and form wrappers. This forces the application logic to be forced in the "controllers".
On the other hand you have glorified templates, instead of proper view instances for containing presentation logic. It is somewhat mitigated by use of widgets, but those instead suffer from SRP violations, because widgets are forced to contain bits of presentation logic and perform partial rendering. The rest of presentation logic ends up again in the controllers.
And to make it all worse, the "controllers" also have to deal with authorization. This usually will mean, that whenever you change the access scheme, you will have to go through every single instance of CController to check whether it needs to be changed too.
It's not MVC. It's a mess with names taken from MVC design pattern and slapped on some components.
All the small things ..
The framework also comes with few minor issue, that do not deserve a separate section:
Defining more then one class per file:
This will get annoying quite fast, because there will be classes that are shoehorned at the class files with completely unrelated filenames. This will mean, that debugging will quite often require use of search.
Slapped on "modules":
By the looks of it, the modules where added to the framework after the fact. Which is why, when you need to set default module, you will have to set it in the configuration files parameter, that is called 'defaultController'.
I actually recently converted a MVC pattern website I had built from the ground up into Yii. It did take some time to set it all up but in all honesty it was well worth it. I was able to throw away a lot of code because there were already Yii extensions doing what I needed. I would also suggest that you keep your database because you can create the controllers and Models using Gii which will save you a ton of time.
I don't know of any quick solutions to this. It depends upon how the code was written. You have the database and your views so it is not really a complete new project when you take into yii. Yii will generate the database models for you. You already have the views from the existing project. Write the controller and actions and modify the views if necessary.
try these links as they refer to the same problem.
How do you convert an old oop project into Yii
tips on migrating an existing site to Yii
Drupal to Yii Migration
Since you already have a code in mvc, things will be much easier for you to migrate. However, while migrating to Yii, since it can generate controller and model very easily using gii, you can take the advantage of it.
So, first generate controller and model using gii, then you can replace your existing code (by replace I mean, substitute your code to the specific function in the controller and model) to the built in controller and model so that the functionality of your site still works. You can modify your view accordingly. But that won't be much of a work.
You can simply register your script for ajax, jquery and css. Those will work as well.
And yes, Yii is the best framework out there so take as much benefit as you can.
Thanks,
Ujjwal
In this project you converted php to yii framework. Its really easy for you if you do following step.
Since you already have a code in mvc, things will be much easier for you to migrate. However, while migrating to Yii, since it can generate controller and model very easily using gii, you can take the advantage of it.
second, If your database is accurate then 50% work complete.when you create CRUD operation using gii then automatically model-view-controller create.if you create mvc in php then it benifit for you.
third,You can simply include your script for ajax, jquery and css. Those will work as well you create a folder in themes(CSS,JS,AZAX,BOOTSTRAP).
four-Protected->view->layout, where you can change your theme..thats all
you also help www.yiiframework.com/doc-2.0/guide-intro-yii.html
if you think my answer is help you then rating me...thank you.
Basically, I started working in a more mvc manner where I have my html, objects, executing code, seperated into views,module, code.
So for example, if I want to create a registration form, I create a folder called "Registration" and put three files:
Registration
--- Views (contains html table and form)
--- Module (contains a class that validates output and inserts the new user).
--- Controller (executes the class in the module file).
My question is the way I work called MVC?
Another question how time saving are the existing frameworks in php eg. ruby on rails, zend framework..
I am a bit new to php and I am not sure if it is worth swaping to one of them 1?!?
Not quite, but close.
MVC stands for Model-View-Controller.
Models contain domain logic. They represent pieces of data, and can handle persistence (e.g. storing/fetching data in a database.)
Views contain presentation (and presentation logic). Some people like to separate the two, creating a View Controller that contains the presentation logic and keep the view simple. Regardless, views are where your HTML goes.
Controllers contain application logic. They typically tie together models and views, and should be fairly lightweight. Most of the heavy lifting is done by the model.
As far as frameworks are concerned, do your research. I would not recommend Zend Framework for beginners, but that's just me. Ruby on Rails is not PHP.
Frameworks are nice in that they help "force" you to be organized, but are not a do-all-end-all solution. Sometimes they get in the way, sometimes they make things really easy.
Just to get you started in the a framework mindset, check out CodeIgniter. While I personally have not used it in a long time, it is a good framework for beginners to jump in to. The docs are great and community is decent.
Try looking into creating your model view and controller through the powershell by typing commands like "zf create controller controller_a" or "zf create project project1" rather than typing out all of that nonsense.
You'll have to configure an environment variable to run the commands in powershell.
I find frameworks very powerful. It's ultimately up to you to decide what you are comfortable with.
The way you work is MVC but i think it would save you a lot of time, switching to a framework that is designed from scratch with MVC in mind. The learning curve is always a bit strange...a bit tough at start but time saving for as long as you will be a developer. If it is a big project i would suggest Symfony2 with Doctrine2.0
I've recently inherited a medium-sized php site which is horribly coded. It violates every best-practices methodology, from MVC to DRY, is vulnerable to SQL-injection and everything in between.
I've visited the other questions and already put everything on a VCS and am considering the framework alternatives. However I'd like your opinions on a framework that lets me slowly migrate from the actual site to a framework controlled one.
Thanks.
Zend Framework would actually be the best choice in my opinion, as it has a great use-at-will structure and it is no full-stack framework like most of the others.
That means that you can start with migrating the model-layer first without having to touch the view or controller part. And even when it comes to the controller part, you could first put everything into controllers without having to rely on the router, so you could still use your old URLs.
I will put my vote in for CakePHP (http://www.cakephp.org). It has the ability to manage everything very nicely.
Template
This will allow you to create the base template / layout for the site. It is the main body of the site. You can store multiple layouts all in the views/layouts directory. You can identify what layout you want to use for any given page within the site.
Static Content
If you have static content pages, they all reside in views/pages. These will load into the layout wherever you put the <?php echo $content_for_layout; ?>.
Custom Code
Many times, you will have custom code that may not fit in the framework. No worries, you can add this to the libs or vendors folders and call the functionality from there.
Speedy Upgrade Via Bake
One of the cool features of cake is the bake feature. Once you have added your schema to the database, you can use bake to have CakePHP write all of the models (with relationships), the controllers (with basic CRUD and admin sections), and the views for each action within the controller.
Cake has been a great fit for all of the projects I have worked on. It keeps the code well organized, has a very active community, and their documentation is very well written and understandable.
UPDATE: For additional information about some sites who use cakephp you can see a sample list here: http://book.cakephp.org/view/510/Sites-in-the-wild
A few notable (high traffic sites) would be:
https://addons.mozilla.org
http://scratch.mit.edu/
Kohana is my framework of choice, but I won't start to wax about its good points, I'm sure it can do anything the others can do.
Faced with the same legacy codebase problem as you described, my response was to take Kohana and disable the request routing, so that you can just use it as an include on a page-by-page basis until you're ready.
The changes are minimal; if you're interested the fork of kohana is up on github
You may need to adjust the php error level settings depending on the kludgey-ness of your codebase ;)
Zend Framework is awesome.
Even better, this excellent post from Chris Abernethy shows how to gradually migrate an existing site from a twisted plate of pasta into a nice MVC structure using ZF.
Take a look at Fat-Free Framework. It allows both procedural and OOP code, so you can have a two-stage approach. If the base code is currently procedural, then you can focus all efforts first on transformation to MVC architecture. That way you can have a proof of concept that all future efforts can be as fruitful as the first phase. Then you can move too strictly-OOP. No other framework will give you this kind of flexibility. And your end-users will not feel any delays, or worse, a culture shock.
You will get as many answers as framework users there are in this place. It's obvious that someone using framework of his choice will advice it to the others.
I opt for symfony.
However, if you care about best practices than both symfony and Zend are a good (and only) choice.
This sounds like a massive undertaking.
I can only recommend CakePHP because that is what I use, but that does not mean another framework would be less or more suitable. They're all pretty much the same when it boils down to it.
Choose on whatever criteria you wish, such as public support/user base (Cake's is massive), feel, name, colours on the webpage, whatever. But my advice is to stick with that choice and ride the learning curve.
All the frameworks mentioned are good, but you will need to rewrite loads of things like the queries. You might not want to use an ORM like Doctrine or Eloquent. Just stick with something like Active Records. Codeigniter, CakePHP and Yii will do just fine.
but it is not going to be an easy task. be warned!