Yii - Dynamically Loading a Controller - php

I have had a good play around with the Yii Framework and now I want to take it a bit deeper and what I want to do is set up an application where several different URLs would point to the same controller.
Normally domain.com/content will point to class ContentController which is standard in MVC.
What I want to do is set up three controllers (maybe more but this will do to start), i.e. ArticlesController, DisplayController and SplashController.
I would then set up what is essentially a CMS for a client, and they would be able to create as many pages as they want and point them to the above three controllers, which I have already set up to handle the data.
So for instance my client could set up the following pages: news, notices, technical and have them all pointed to the ArticlesController, and also set up pages: management, specials, support and have them all pointed to the DisplayController.
I know that all those controllers could be creating using the Gii module, but in this case its not an option as I don't think that's suitable for non technical people.
I just want my client to be able to log into the CMS, decide he wants to create a new page called "randompage", point it to the ArticlesController using a drop down menu, then write a bunch of articles for it and now have those articles accessible at domain.com/randompage/article-1 domain.com/randompage/article-2
With the standard set up that would point to site/error because there is no controller RandompageController
What I've done so far is create a constructor in Controller class where I can overwrite the controller id
class Controller extends CController {
function __construct($id) {
// Code here which successfully pulls from the database
// which controller the current page should point to.
parent::__construct($newControllerID)
}
}
If I check in the CController class, $this->_id = either articles, display or splash but the application itself stills loads site/error
I'm guessing I must have to set/override the Controller elsewhere. I have tried
Yii::app()->setController($newControllerID)
but that doesn't have any effect
Perhaps Yii is set up and must require a specific controller for each URL but that would mean developing rather rigid solutions for clients, and requiring them to call in the developer every time they want to add a new controller.
Hope I have explained what I'm trying to do well.

create a page object (id, title, slug, description, image)
create an article object (id, pageId, title, slug, content)
configure your urlManager:
'<pageSlug>/<articleSlug>' => 'article/view'
in your ArticleController->ViewAction evaluate
Yii::app()->request->getParam('pageSlug')
Yii::app()->request->getParam('articleSlug')
to find the right article for that page

Related

how to make news and articles using the same silverstripe news module?

I need to incorporate News and Announcements in my silverstripe website, both news and announcements have the exact same structure and they both use https://github.com/nyeholt/silverstripe-news. in the html template I have two sections one for the news and another for the announcements.
what is the proper way to implement this:
should I just copy and past the /news module folder and use one for the news and the other for announcements.
or add another db field as flag to specify if this is a news article or an announcement article, but then in the cms the user would have to check this every time.
or is there anything else, I don't know
Duplicating the folder would not have the result you expect unless youd rename all the classes in side of the new one.
Basically the folder is just a place for the classes to be, not something that you access when you actually request an news article, you use SilverStripes routes for that.
Static assets would be something that are be loaded from a module folder.
The best way to add a new behaviour to an extension is to use a DataExtension.
See https://docs.silverstripe.org/en/3.4/developer_guides/extending/extensions/
Other way would be if the module uses sitetree for placing the "news holder". Then you have the option also to just create two holders with different names and then if you want to show a list of a paricular parent just filter with the parentId that relates to the correct holder.
Third option would be to just would to add a new class under mysite that extends the modules classes and override only SOME of the methods to suite your needs.

Location of admin controller methods

I am building a Laravel 4 application and I am trying to sort out where my admin controller functions should go.
eg my admin user view, edit and update functions.
Previously in my User controller, I would have
function getIndex()
{
// Get method for normal users
}
function getAdminIndex()
{
// Get method for admin users
}
I would then have in the routes /users -> getIndex() and /admin/users -> getAdminIndex()
however, is this ideal?
The reason is it makes my routes file quite large as I have to specify every route.
With things like Blog posts, and Products, should I have one controller for logged out / user access, and then a separate controller, in an admin folder for just the admin functions?
Is there some open source projects I can look at?
You should separate your regular controllers from your admin controllers. It's a matter of personal preference how you do it: you can create folders inside your controllers folder, or maybe you could create –almost– independent modules with controllers on their own.
For the first option, take a look at this project:
https://github.com/andrew13/Laravel-4-Bootstrap-Starter-Site
For the second one, which is a bit more complex, you can get inspired from this post by Ryan Tablada:
http://ryantablada.com/post/juggling-larger-laravel-applications
I personally prefer this last one if the project is medium/large size, and the other one if it's a small project.
You can also try Laravella, a CMS, CRUD, Bootstrap, Uploader etc. framework for Laravel.
https://github.com/laravella/laravella/releases
If your project is small, then you can use Resource Controller.

Structuring classes and objects in CodeIgniter for future upgrades?

I'm new to Codeigniter and pretty new to OOP as of the last month or so. I've been playing around and have been trying to make a blog page with a list of 10 posts and have different functions and possibilities for each.
For example, in the future I want to be able to show different buttons below posts depending on whether they are a logged in user, or if they are the post creator, etc.
Would I be best off making a new class 'blog_posts' and making an instance of it for every post I show on the page? like:
$this->load->library('blog_posts'); // in library or models, I'm not too sure?
$new_inst = new blog_posts;
$new_inst->show_post();
My end goal is to get it all as easily updated, changed, or modified in future if needed, I've seen simple tutorials online:
http://blog.pisyek.com/2011/03/create-a-simple-blog-using-codeigniter-2-0-part-1/
But I can't see them being easily updated and modified in future. I haven't seen a lot of other CI apps using new instances of classes, so I'm thinking there may be a different way in CI? Are new instances used in CI a lot?
Start with the controller. With Codeigniter -- anything you can do in a model, you can do in the controller. The easiest way to start -- just put your methods in the controller and set up a simple view file.
Always do a simple sanity check to make sure the basics are proper. Set up a controller and echo out some text.
In the controller try:
Get blog posts from your database using active record commands
Pass the blog posts result to $Data
With each step, Echo out something in the controller to confirm that its working
Next -- try using $Data to pass the blog results to the view.
After its working and you understand the basics -- then start pushing your methods to a Model. As you refactor and clean, your controller will get 'thinner'.
typically for blog posts you would have one model, that would return the blog posts and might also have your insert / update / delete methods. i say might because it usually makes more sense to have a public blog controller, that just shows blog posts. and then a separate blog admin controller -- that is only available to users who are logged in.
These two controllers - can share the same blog model. So for example to show blog posts on an admin screen - you could use the same method as showing the posts on a public page. Whereas you might have an admin blog model -- which has the create / update / delete methods.
That way you enforce a very clear separation of User Roles from the start -- people who are viewing the public blog should not be able to delete posts. The public show blog class is not "responsible" for editing.
This is something that i'm grappling with -- like the normal way to demonstrate a blog is to have all the methods together. Which makes sense in terms of "what can we do with a blog post" -- but it doesn't make any sense in terms of user roles.
ok Next - work on your create and update and delete methods.
Next try creating your log in methods. Make the Login process separate controller / model / view.
Eventually you could have one method call in the constructor of your blog admin class that checks to make sure that the user is logged in - otherwise it redirects them to a login page. That way you dont have to check over and over again in the view files etc to make sure they are authorized.
( highly recommend the free codeigniter tutorial series on net tuts website )
more rambling:
looking at the process from the point of view of the actor (user,role) -- for me helps to clarify what the chain of control should be. really critical roles - like an admin that has the power to delete all blog posts - the system should know that role at the top of the class.
best 'worst example' is when there are "is this a super admin?" checks in the view code. the view should not know anything about admin roles. BUT MUCH WORSE when you put a reference to an admin role in some view file -- what happens when you want to change that admin role in some way? now you have to go into all your view files!
class and method names - i'm moving towards not revealing any business or crud or field or any other type of business information in the URL. no nouns no verbs no ids. as simple as possible, with very few public url 'doors' into the app.
whats wonderful is that codeigniter makes it really easy to make your methods private. for critical pages: only use the public index method in the class for redirecting and make all other methods private.
use routes that directly to private methods. or public methods with broad names, that if successful -- like you have confirmed their credentials - go to private methods in the class like $this->_showAdminPage()
this is where defining a role like - blog editor - makes things very clear from a functionality point of view, AND keeps the valuable business knowledge private.

Need a light understanding MVC pattern

You have the URL:
http:///www.site.com/controller/method/values/1/2/3
Do I have to always have the controller being called or can I have the view being called and instantiate the controller inside the view or in a bootstrap file referring to this view?
What I don't get it is if I need more than 1 controller on the view, how to archive that?
For example:
On my index page I want run a simple CMS, where the admin can change the text blocks and images of the site. That would be on the content management controller.
On my index page I also got the latest added products vitrine, what would be controlled by the controller products.
If I define www.site.com/contentmanagement or www.site.com to run the contentmanagement controller, how the product controller would be called?
Also, another example. On my menu I got a link to a page called aboutus, that would be a simple page and the only feature needed would be the content management controller to manage the texts blocks.
If I follow the pattern Im reading all over the place I will end with a link like:
http://www.site.com/contentmanagement/method/aboutus
?
Kinda lost here cause surely this URL will look weird. Would be much easier to have the URL calling the view http://www.site.com/aboutus and a boot file where I can tell the controller that should be loaded when the surfer is there ...
bootstrap would look like:
switch($view)
case: index
controller load contentmanagement
controller load product
case: aboutus
controller load contentmanagement
I appreciate any help or a light here, thanks.
by the way, Im coding in PHP.
Hm, if you want to have text blocks and images of the site (one controller), and products vitrine (second controller), then call the methods you need in one controller..
I would do it this way: when you request index page with all the elements you mentioned above, actually one controller is called, and it decides which view to show.. so in that controller, you call the all methods that you need, get the data, and pass it to the view.. if the methods are called from other controllers, just call that methods and get the data.. i often make some static methods in controllers, which I can call anywhere, so I don't have to instantiate whole object..
E.g. you call www.site.com/contentmanagement, controller is called, which will display index view, and in that controller, you call all methods you need, prepare the data, and pass that data to the final view which will be displayed..
Do I have to always have the controller being called or can I have (..blah blah..)?
It kinda depends on what you understand by "call".
Controller needs an ability to change state of both View and Model(s).
And each View need ability to request data (in Model2 MVC) from Model(s).
Thought Controller should not cause the rendering of View (which is common in all the RoR sycophants) much like View has not business in executing actions on the Controller.
What I don't get it is if I need more than 1 controller on the view, how to archive that?
Views and Controllers should have 1:1 relationship. If your view need more then one controller, you might want to look into HMVC architecture.
For example: On my index page I want run a simple CMS, (.. more blah .. ) how the product controller would be called?
CMS should be a separate application ( or at least module ) with multiple controllers.
If I follow the pattern Im reading all over the place I will end with a link like: http://www.site.com/contentmanagement/method/aboutus ?
Why not just http://site.com/cms/content/2/edit (where 2 is the ID for "about us" page). There is no law which states that URL structure for site administration must mirror the publicly available page .. hell .. it can actually cause increased vulnerability.
I am going to try to walk
What I don't get it is if I need more than 1 controller on the view,
how to archive that?
For example: On my index page I want run a simple CMS, where the admin
can change the text blocks and images of the site. That would be on
the content management controller. On my index page I also got the
latest added products vitrine, what would be controlled by the
controller products. If I define www.site.com/contentmanagement or
www.site.com to run the contentmanagement controller, how the product
controller would be called?
Having the URL to contains the controller's name is definitely nice, but it is not the requirement for MVC. So you don't have to necessary map your controller to the URL itself. A classic MVC does not tie itself to a particular naming convention, so you could call your product controller via different URL which then process the product and show the view for the product.The important for MVC is to have one controller that deals with sets of model and resulting in one view as the presentation layer. In your particular example, your entry point seems to be a single controller that interacts with both ContentManagement and Product Class/Module and the resulting interaction produce a single view.
bootstrap would look like:
switch($view)
case: index
controller load contentmanagement
controller load product
case: aboutus
controller load contentmanagement
Thus your original interaction above is not completely off, except that you are not really calling two controllers, but rather doing the following upon hitting index:
Load a controller, let's call this one IndexController
Load ContentManagement module to get the related content, you might want to put the info as part of your Model for the Index page
Load Product module to get related products, again put this into your Model
Pass the Model containing the info for rendering the page into the View
In your View, you render the Model that contains both Content from ContentManagement module and Product list from the Product module thereby producing a single view
If I follow the pattern Im reading all over the place I will end with
a link like: http://www.site.com/contentmanagement/method/aboutus ?
This is again not a requirement, you should follow what makes sense and easier for the users. Also, if you are required to follow the conventions, you could always make your URL pretty by using URL mapping.
What you are looking for is called HMVC and there are a couple of frameworks for that out there, like Kohana.
Also see this question:
What is the HMVC pattern?

Adding interactions to admin pages generated by the admin generator

I am using Symfony 1.2.9 (with Propel ORM) to create a website. I have started using the admin generator to implement the admin functionality.
I have come accross a slight 'problem' however. My models are related (e.g. one table may have several 1:N relations and N:N relations). I have not found a way to address this satisfactorily yet. As a tactical solution (for list views), I have decided to simply show the parent object, and then add interactions to show the related objects.
I'll use a Blog model to illustrate this.
Here are the relationships for a blog model:
N:M relationship with Blogroll (models a blog roll)
1:N relationship with Blogpost (models a post submitted to a blog)
I had originally intended on displaying the (paged) blogpost list for a blog,, when it was selected, using AJAX, but I am struggling enough with the admin generator as it is, so I have shelved that idea - unless someone is kind enough to shed some light on how to do this.
Instead, what I am now doing (as a tactical/interim soln), is I have added interactions to the list view which allow a user to:
View a list of the blog roll for the
blog on that row
View a list of the posts for the blog on that row
Add a post for the blog on tha row
In all of the above, I have written actions that will basically forward the request to the approriate action (admin generated). However, I need to pass some parameters (like the blog id etc), so that the correct blog roll or blog post list etc is returned.
I am sure there is a better way of doing what I want to do, but in case there isn't here are my questions:
How may I obtain the object that relates to a specific row (of the
clicked link) in the list view (e.g. the blog object in this example)
Once I have the object, I may choose to extract various fields: id etc.
How can I pass these arguments to the admin generated action ?
Regarding the second question, my guess is that this may be the way to do it (I may be wrong)
public function executeMyAddedBlogRollInteractionLink(sfWebRequest $request)
{
// get the object *somehow* (I'm guessing this may work)
$object = $this->getRoute()->getObject();
// retrieve the required parameters from the object, and build a query string
$query_str=$object->getId();
//forward the request to the generated code (action to display blogroll list in this case)
$this->forward('backendmodulename',"getblogrolllistaction?params=$query_string");
}
This feels like a bit of a hack, but I'm not sure how else to go about it. I'm also not to keen on sending params (which may include user_id etc via a GET, even a POST is not that much safer, since it is fairly sraightforward to see what requests a browser is making). if there is a better way than what I suggest above to implement this kind of administration that is required for objects with 1 or more M:N relationships, I will be very glad to hear the "recommended" way of going about it.
I remember reading about marking certain actions as internal. i.e. callable from only within the app. I wonder if that would be useful in this instance?
I'm assuming your application is called backend. Suppose there are two models, BlogPost and BlogPostComment. These are managed using admin generated modules called blog_post and blog_post_comment.
I believe you want a link against each BlogPost displayed on the list page at backend.php/blog_post. The links take you to backend.php/blog_post_comment, which should only show comments related to the relevant BlogPost.
Under apps/backend/blog_post/templates, create a file called _commentslink.php and put this in it:
View Comments
Then in apps/backend/blog_post/config/generator.yml, you need to include this partial in the fields for the list view:
....
param:
config:
list:
display: [ id, title, _commentslink ]
Note the _commentslink - the _ tells it to use a partial instead of looking for the field in the model. Your object is available in this partial as $<name of model> - $blog_post in this case.
Essentially, all this method does is links to the same action as the filter on the comments list normally goes to, passing the relevant condition to it to make it filter by blogpost_id.
If you've got CSRF protection enabled in the backend, you'll need to disable it, or this method won't work. This is set in apps/backend/config/settings.yml. There will be a setting in there called csrf_secret - it should be set to false to disable csrf.
You should try symfony 1.3/1.4 out if you need support for 1:N relationships in forms. 1.3 is in my experience a relatively hassle free upgrade from 1.2.x - 1.4 is the same, but with deprecated features removed.

Categories