Well, I have been thinking a lot about the first real CodeIgniter site I am coding. I want to modularize the site in such a way that I have a controller that formats the navbar, one that formats a multipurpose right column, and one that formats the content area.
My idea is to have a controller for each state of any part of the site (an example would be the right column, it would have 3 states; new posts, related posts, and search filters). I would also have the content area be many different states aswell (things like search results, view post, new posts, etc).
The problem is that I can't find a way to take multiple controller outputs and compile it into a single template (notice, I said controllers, not views).
I have seen the HMVC extension, but that is going to far for my first site, and am hoping for a more simplistic solution (unless you can prove me wrong, and show that HMVC is easier than what I've seen).
This seems a little wonky to me in an MVC model.
If you're using a single stateful view for your right panel that might change state based on input (i.e. which page the user is currently on), then I would add a model for the panel. The controller's action would be responsible for setting the correct model state (i.e. "you're in home page state"). The model could be responsible for telling the right panel view which child views to load.
That's how I'd probably implement something like that anyway. HMVC seems overkill and with this example, wouldn't be used as intended.
For what you're trying to accomplish the matchbox module suggested in the comments seems way overkill. I don't think that using controllers to format each of these areas is a very good approach to take.
Usually people who want the type of functionality that you're describing when working with CodeIgniter end up using a template library. There are several open source template libraries for CodeIgniter that can easily be found with a google search for "codeigniter template library".
I've never used any of them so I will not recommend any particular library. However the app that I'm working on has borrowed some ideas from Phil Sturgeon's template library. You may not find an exact match to features that you need but at least you'll be able to draw some inspiration from solutions that others have come up with.
Related
I am currently trying to understand how the MVC framework does work in PHP. Therefore, I have created this basic sketch of how I think that MVC is implemented in PHP:
[I know that some steps are missing, e.g. how the Routerparses the route in order to know what View and Controller to load, but these steps are rather technical based and are not important in order to understand the general flow of MVC in PHP.]
I draw my understanding of MVC in PHP from this article series. However, I think that this structure will differ from most of the structures people think off, when they talk about MVC in PHP, because of this article (The article basically states that not only the Controller but also the View does communicate with the Model).
What I'd like to ask you now are several questions:
Is this generally a right way of implementing MVC in PHP?
How can I add a Login/Logout-System to this approach? So that user, who are not logged in, will always see the LoginView and users who are logged in can see different views? (I know how a login system does work, but I can't figure out where to place it in the MVC, so I don't have to insert the code multiple times, e.g. in each Controller.)
What if my application consist of multiple elements (say a user bar [with user name, link to settings, etc.], a navigation and a content container) that are always loaded? How can I assemble these elements to a final view? (The only idea that comes to my mind is to assemble the final view in each view separately, but that would mean that I have to insert the code for it multiple times in each view, which misses the point of MVC, doesn't it?)
What if I want to use AJAX in my application? My idea would be to send ajax requests through the framework as well, while only accessing controllers and views that are made for ajax? In other words the AjaxViews do only return e.g. json objects and the AjaxControllers do always expect authentication codes to prove that these ajax calls are legtitim?
I know that there have already been asked dozens of questions about MVC in PHP and I've been reading quiet a lot of articles until now, but I think that only reading does not enable me to understand MVC completely.
Furthermore, after reading the articles linked above, I'm not longer sure whether other articles about MVC, I find on the web, does explain MVC the same way as the articles above. Because if they don't, I'm trying to understand one framework while reading about two or multiple different approaches.
Thank you very much in advance for taking the time to answer my question!
-- --- --- Update --- --- --
According to the answer below I've changed my MVC sketch. Just in case someone finds this link and wants to know more.
Let me first answer your questions, then place my take on it.
There's no right way of writing MVC. There are so many flavors and variations, and that get even multiplied when talking about web MVC.
About Logging in and Logging out. I think the most robust system would be a Role Based Access Control combined with an Access Control List, see How can I implement an Access Control List in my Web MVC application?.
There are generally two approaches, either you have a 1:1 ratio between Controllers and Views, and then after the Controller is done, your bootstrap script calls the View with the same name (LoginController, LoginView), or your Controller returns the View name along with action and parameters, to be called by the bootstrapper. The view then picks a template, and that template can include other sub-templates (like the user bar, or the footer).
In that case, your view needs to have an ability to select a different template based on the Accept: HTTP header (and send something like Accept: application/json in your AJAX requests). Your view then returns a JSON template instead of an HTML template.
What is wrong with your sketch?
Your model isn't just the gateway to your database, it's where all the logic happens. All the computation. See this yet another excellent answer that explains How should a model be structured in MVC?.
The idea of MVC is to simply separate your application into three layers: Input (controller), Logic (model) and Output (view). This is to extend on the usual way PHP works (here's a request, give me a response, all in the same page).
For that reason, implementation details may vary, the concept is what matters. "Web MVC" is merely the result of good OOP practices and some naming convention someone made up a few decades ago.
It is for parallel development and code reuse ability. There is a separation of concern how your system works and how users work. This provides a solution of the problem. There is boundry now, MVC.
I have a large complex web site currently implemented using PHP and MySQL.
Some of the pages (about, contact us, etc) are largely static, but need to be updated from time to time. I'd like these updates to be able to be done by non technical admins, so I'm migrating the site to Joomla CMS. I've created a Joomla template to reproduce the banners, styling etc of my existing web site and have successfully reproduced the static pages by cutting and pasting into Joomla articles.
I'm now trying to embed my existing dyanamic php pages into the Joomla framework. I assume that I need to convert them into one or more Joomla components? I realize that I'll need to strip out the php code that currently generates banners, menus, etc, but I don't want to make major changes to these php pages, i.e. I don't want to re-implement them to follow an MVC pattern. I'm looking for a simple Joomla 3.2 hello world component tutorial. The tutorials that I've found are either too complex (i.e. MVC) or they're "too simple". By too simple I mean the component is not listed when I select Menu Item Type within the Menu Manager. Can anyone point me to any documentation that explains the minimal config that I need to include in a custom Joomla 3.2 component in order for the component to be listed when selecting Menu Item Type?
Also, should I create one big custom component to wrap my existing PHP application containing multiple pages("views"?)? Conceptually there the system could be considered as about 3 sub-systems, but there is some overlap between the MySQL tables used in these different sub-systems.
I don't need the implementation to be portable, i.e. I'm not trying to create a reusable component that others could use, I just need it to work on my site, using the least amount of work possible.
Thanks, Wayne.
I hope to clarify a bit and give you way out.
In response to your comment on #user3057084, the power of Joomla and its flexibility comes from it being MVC! If you want to wrap your existing code with little modifications, Wordpress will let you do all kind of nasty things! Nasty in the sense of mixing logic with data, i.e. copying and pasting your code and getting it to work quickly.
Joomla coding standards require that you separate models from views. And that you understand how the Joomla MVC implementation works. It will take longer, but you'll learn a useful skill that can and should be applied if you want to write portable maintainable code following Design Patterns.
Now about the way out.
Nothing keeps you from putting your raw php code in a Joomla view, including the database access. It's really ugly and I feel bad even suggesting this, but if it can be a small step towards using a great framework, then the end justifies the means.
The absolute easiest way for you in Joomla would be to create a template override (which you'll do from the admin with a few clicks in the template manager), then throw your code in, and it will run. Then, a little bit at a time, you might learn to separate the parsing of the input in the controller, store / retrieve the data in a model, and leave just the markup in the view.
But are you absolutely sure you need to code for this? There are thousands of (free) extensions out there that might do the job for you with no coding and little configuration, leaving you just a data migration to handle.
Have you had a look at Wordpress yet? In my experience, non-technical people find it easier to administer a wordpress website in comparison to a Joomla website.
When it comes to the menu structures,themes and contact forms and blogs - Wordpress takes the cake.
It would be worth your while to check it out? It might save you hours of frustration?
I'm starting to look at Object Oriented PHP. To date I've developed a large number of PHP systems with a procedural approach, but I think it's time to move forward.
One of the projects I'm working on at the moment is a Grade and Handicap Calculation plugin for WordPress. In short, the plugin takes table tennis players' results from uploaded CSV files and works out their grading for handicap tournaments.
I'm using WordPress because my table tennis club's website uses WP and if it works for them I can potentially give it to other clubs/leagues and they too will be able to install the plugin and have access to a fully-fledged grade and handicap system.
Outside of WordPress, I'm reasonably confident that I could develop such a system in OO-PHP using the MVC pattern. It would probably look something like this:
Controller
Create an instance of the Model
Deal with "navigation", i.e. GET/POST requests, and work out which page templates to display accordingly
Model
Deal with uploading and storage of files
Update and select information from database
Host mechanism for working out players' grades
View
Admin pages, i.e. settings and uploading files
Grades page, displaying players' grades and handicaps
Results page, where specific users can see individual players' results (mostly for debugging purposes)
Please correct me if I'm wrong, as I've only learnt this pattern in the past 30 minutes or so, but by my logic that is a true MVC approach to creating this system.
However, once I bring WordPress plugins into the equation, I'm starting to struggle with the following questions:
In the non-WP system, CSS styles would simply be included in the View's PHP pages which I'd then include in the Controller. However, in WordPress, it doesn't work like that - I can't use CSS styles in that way, they have to be enqueue'd. Where would I host the function for enqueueing my CSS files?
When someone first activates the plugin, it will need to create the appropriate database table using WordPress functions to do so. This would then have to be run off a hook, i.e. a register_activation_hook. Where would I host these functions? It would seem sensible to put them in the Controller but at the same time I'd imagine that maybe the Controller needs to be kept as clean and simple to read as possible.
Similar to the above question, I also need to create WordPress admin pages using add_menu_page and add_submenu_page commands. Where do I host these functions?
All of these questions probably have the same answer, and I know it's just semantics, but I'm keen to try and get this right early on so I can truly get my head round the MVC pattern of Object Oriented PHP.
Thanks in advance,
If you are looking for a better place for learning MVC, this would be it.
Hope I'm getting this right.
Can't tell you about CSS, as I just keep those defined in my layout files (view).
Heavy logic can be put into services (external Class), and then being ran in controller. You'll keep your controller 'thin'
Similar to previous one. You can have your menu stored as a model (which doesn't have to be strictly DB related, but also XML/JSON/array data), and then call your add/remove actions in controller.
Sorry for the confusing title....
We are developing an application to be used by multiple companies. For the most part, the application is the same, your standard sort of database manipulation pages (search pages, edit pages, etc.) customized for the data that it is designed for.
However, each company has a slightly different process, and we will be dealing directly with each company so we'd like to use some sort of system that would allow us to tweak pages depending on which company is viewing the page. For example, one company might want a couple extra fields on a data input page, or another company might want to view a different piece of data on a search results screen, and so on.
I understand this is all hypothetical and I wish I had a concrete example to give you, but honestly the companies haven't even given us very good examples. We just want to be ready.
So my basic question is, what is the most flexible way to allow for these tweaks and customizations on a per-company basis? Obviously, the most flexible but least programmer-friendly way would be to make a complete copy of the app for each company. This obviously isn't an option because we'd need to manage updating code on all the sites, trying to keep them all running and tested and having issues resulting from the customized code.
What are your thoughts on Smarty being a solution to this? Perhaps if we have a master set of templates, but then each company can have a different subfolder with any replacement template files... Of course we'd still need to update a bunch of different template files whenever we change one of them, but it would be a little more localized anyway.
Is there a better way? Some sort of differencing template engine maybe, so that we can still edit the original files and the changes will adapt on top of the originals (kind of like a patch)? Or perhaps we should use the object-oriented features of PHP5 and then use polymorphism? What is your best suggestion, and especially if you've had experience with this sort of thing, what are the options and which have you used and why?
I think the template method pattern will help you out a lot. It's really a great pattern for factoring stuff that is mostly the same but differs in a few places. I'm actually working out a template method hierarchy for my own project right now.
I would suggest you try to create the application either using an mvc framework or using your own implementation of mvc.
In this manner you could create models that could be reused (and also views) for other companies.
I have a pretty large site, and I am looking for the most time efficient way to manage it (I am the sole coder).
I am trying to devise a very simple MVC structure (i don't want to use a framework) to help keep all my code in order.
For a huge site, is it better to have only one controller to handle all the pages, or is it better and easier to split them up?
If just one, what is a good example of a non-framework controller?
I would split any logical divisions into different controllers - if it's all static pages, then serve it up with all the same 'static page' controller.
If you have some static pages, a FAQ page (or section), a product list - use a controller for each different section. So the static pages would be pulled from flat files or a database by one controller, the FAQ pages would be generated from a FAQ table by another controller, the products and info would be generated by whatever the source for that is.
Every time the way a page is generated or the data is accessed, use a different controller.
Of course, class inheritance can be used to create the base class with the code needed by any controller.
Not sure what you mean by a non-framework controller - I'd checkout the Zend (gasp) 'Framework', the MVC pattern, and even the controller itself, can be used apart from the rest of the framework.
I tend to split the controllers up based on their responsibility to a specific section of a site/application. This makes maintaining the code so much easier. Furthermore, I group controllers (and views, models) within modules (folders). Here's an example from a current project I'm working on:
Blog
Posts
Comments
Categories
Settings
Posts
Users
The more complex a site, the more modules I use. Although most of my modules only contain one 'Index' controller, I do like the organization they provide.
Then I use a router (front controller) that maps a REST style URI to the proper module / controller / action. Ex: mysite.com/blog/posts/view/7 would call Controller_Posts::view(7) from the "blog" module. An added benefit of using modules is I can have more specific URIs than if I didn't have modules. Although I suppose that could be remedied by using a router that supports defining custom routes, but I'm not too fond of that.
As many other things, it boils down to what you're comfortable with as a developer, but we can probably agree that more organization you have, the better off you are, so long as you don't over complicate things.
As a quick aside, I would recommend you look into using a framework. I understand if you don't want to use one of the ones out there already, as I avoided those too. I ended up writing my own which for the past year has served me very well. It was a great learning experience and it only contains what I want / need. That being said, you might want to look into Kohana and CakePHP - they're not overly bloated IMO and they will definitely save you time should you decide not to write your own.
Typically people split up controllers into controllers focused on specific areas of functionality.
Then they stick a "front-controller" in front of it all, so there's only one entry point to the application. The front-controller's only job is to route incoming requests to the appropriate controller.
Look at the way the Zend_Controller component is set up. It may provide everything you need, and you're free to use it without buying into the complete Zend Framework.
It depends how you other parts will work. If you only have one model file then it's probably not worth splitting up the controller. If you can split up the model into sections as well as the controller, then do that.
However, I often find that there's too much overlap between models to separate them. You might have a model for articles, but if you want to display the top 20 articles in a sidebar on other pages, that code should be in the article model - and you're going to need that on every page.
Honestly though, the only way to do it is try it and see. Start with a single entry point, and if it gets too, unwieldy, refactor it into smaller chunks.
One router/dispatcher, many controllers would be my advice. Controllers ought to map to URLs, which means differing functionality. A controller will collaborate with different services to accomplish each use case, so one controller for your entire app would become too unwieldy if your app has more than a handful of use cases.