This might be an obvious thing to you but - even after reading through a lot of manuals and blogs - I'm still not sure what exactly should a bundle in Symfony2 represent in a webpage. And it's hard to guess it from the simple demo applications.
For example: I have a site which is divided into two parts (one is just a 2nd level domain like example.com and another is dom2.example.com). Each of these two parts has some sections of it's own - sometimes the same (like news) sometimes different.
What would the correct representation of this in symfony2? Should I have
a MySite\site1 and MySite\site2 bundle and do the different sections via different controllers, or
bundles Site1\News and Site2\News, or
bundles MySite\Site1News and MySite\Site2News etc.
...or am I getting all wrong at this?
I am also new to Symfony and will follow the results of this question with interest, but for what it's worth, my take on it is:
A bundle is just that: a group of files, assets, PHP classes and methods, tests, etc. The logic of the grouping can be anything you like. In some cases, it's really obvious what the grouping is and why it's been done -- for instance, if I wrote a blog system for Symfony2 and wanted to release it, I'd make it into a bundle. That's the sort of example used most in the documentation.
But you'd also use bundles for anything you wanted to release as one little feature. Say for instance, this bundle which creates default routes for all your controllers. It's not a fully developed plugin/feature like a blog or forum, but it's a bit of code that I can easily import into my project, it stays totally separate from everything else, it's a bundle.
Finally, you'd also use bundles internally to your project, in absolutely any way which makes sense to you.
My take on your specific situation:
Quick and easy:
MySite\MyCode -- gets the job done, and maybe you don't have any logical way to break up the code you're going to write.
If there's some more unique features between the two sites and you want to separate them out for clarity:
MySite\SharedFeatures
MySite\Site1Features
MySite\Site2Features
If you really like everything in its place, or if you have a complex project, maybe:
MySite\MySiteMain (shared features and catch-all miscellany that doesn't deserve its own bundle)
MySite\News
MySite\Site1FeatureSomethingOrOther
MySite\Site2FeatureSomethingOrOther
I definitely think you want to stick to logical groups of code -- so I think your example "bundles Site1\News and Site2\News" and "MySite\Site1News and MySite\Site2News" wouldn't be the best way to go. Site1 and Site2 are implementations, so making a separate bundle for each site's news page would seem to be counterproductive to me; you'd want to make one news component and build it to be used in two different ways.
As for your two-domains question, you can either point both domains at the same code, and test within your code for what domain is being requested, or you can check out two copies of the same code and change the configuration files slightly (this doesn't necessarily violate the idea of DRY because you'd still edit the code in one place, then update both copies.)
The way I understand a bundle is that it is similar to what CMS like e.g. Typo3 or Drupal call a "plugin". So it should be ideally self-contained and written in a way that it can be used on other projects too.
E.g. in your case I'd create a "staticHtmlBundle" that contains all the static pages of your website, divided within by site.com and dom2.site.com.
Then I would create a "newsBundle" that contains all the news-articles, maybe even database-driven with a little admin-section where you can edit them and assign them to different channels (in your case that is site.com, dom2.site.com). A static page from within staticHtmlBundle would call newsBundle and display its data (like e.g. a listView of the news or a detailView and so on).
If you keep everything as abstract and reusable as possible then you could even publish the newsBunde in the Symfony 2 Bundle repository and share it with the community!
The way I perceive Symfony2 bundles is that they are provide a modular system which allows you to not only extend and override the php code, but also any resources they may or may not include.
Having said that, consider you have an API and you would like to transfer an object.
How would you do that?
Of course, you can do that manually, but wouldn't it be nice if Symfony can do it for you?
My way of doing this would include 3 bundles, JMSSerializerBundle and FosRestBundle.
One bundle for the client side - MyCompany/ClientBundle
One bundle for the server side - MyCompany/ServerBundle
One bundle housing all the data transfer objects I would like to be able to transfer - MyCompany/CommonBundle.
Inside my MyCompany/CommonBundle I would have the classes I would use for my data transfer objects along with the serialization rules I would have to provide the JMSSerializerBundle with. They may be in the form of xml, yml or php annotations.
Once you have an object filled up with the data, you can just use return and FosRestBundle would serialize it for you. Serialization would depend on the routing, so you can have the object serialized in XML for one system and in JSON for another. Key point is you have different serialization formats and versioning you can utilise at later point.
On the client side, you can use simple param converter to convert the received JSON or XML to an object right in the controller with no additional hassle. You can also type in some validation rules, so you can verify if the object is populated as you expect it to be.
In my example, the MyCompany/CommonBundle has objects that would be used by multiple applications and would be identical. Having that as a separate bundle helps you avoid code duplication and makes long term maintenance a lot easier.
I hope I managed to explain this. Any questions?
Ask in the comments. Will update the answer accordingly.
Related
I'm working on a task management application for use at my company. Part of the spec is to create a plugin system that lets users customize and extend the functionality as they need, or as their department requires. I'd love to do this in a really elegant and modularized way, but I'm having a hard time figuring out how.
Consider a view that's a task list: each iteration of the generating loop adds a pre_task() and post_task() call on either end, which builds the interactive pieces on either end of the task title (Complete checkbox, comments link, etc). Now, when the system detects and includes the plugin file plugin_time_tracking.php, the plugin should add functionality to post_task() - adding a "track time" button in addition to everything else.
What I'd like to accomplish is making the plugin "hook" onto pre_task() or post_task() - let it do all the legwork by attaching itself to the proper functions and extending them, instead of having the core sort plugins and herd their functions to the right places. Does PHP offer such functionality? Am I going about this the wrong way? Let me know if I need to clarify at all - thanks for the help!
The boys of Qafoo gave a talk about modularity on the 2012 edition of the PHPBenelux conference. They presented various options to create modular applications such as hooks, patching and inheritance.
You could check out the slides of that presentation here.
I think you should really use a framework that has a built in plugin infrastructure with capabilities to override/inherit. As an example, let's say Symfony2: in sf2 you could create FormType classes that build the form objects (which then pass certain data tot he view). So in this case to add fields another team would simply need to extend your FormType and modify the build to add new fields. Further the Form Api supports embedding subforms so if they want time track then then just need to embed that in the task form or "turn it on" through whatever configuration facilities you supply.
Similarly with render things, you can define override the view template simply by providing at a different level or referencing a different Bundle (a plugin of sorts).
Now Symfony2 is very complex and it has a high learning curve so it may or my not be the framework you should choose, but something along these lines would be more than appropriate. The WP/Drupal pattern of "hook" functions is incredibly annoying to work with, especially if they are building HTML strings on a deeper layer and not giving you the raw data to output as you see fit.
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 symfony app that provides REST based services. I have one module that is responsible for user login/logout/register actions called the UserBundle.
I have other bundles that provide resources once a user logs (and is provided a token hash).
Now for every resource requested, the client sends the token back which needs to be authenticated. Where exactly do I place this authentication function? I mean I know it needs to be a service that can be injected into multiple bundles but does that mean it is best I create it's own bundle? What about additional services that I may need in future? If I create a bundle for each, then my code organization would get ugly real quick.
Any tips?
I would put the service in UserBundle, since the UserBundle deals with authentication.
Generally I like to place services into the bundle to which they are most relevant. I also typically have a "Default" bundle into which I aggregate a limited number of truly generic services, entities, controllers, etc. In theory anything that goes into Default could be used generically in another project and is almost always something required by more than one other bundle. Occasionally I have bits and pieces in Default that mature to a point where they would make more sense in a more specific, yet still generic, bundle (similar to your UserBundle.. I figure it's probably something that can be dropped into more than one project); these get refactored and named accordingly.
Once-upon-a-time I used to split out new bundles for anything I perceived to be a "module". These days, however, I try to limit the number of bundles in an app.. I've found this to make the code more clear and easier to manage; especially since my idea for any given module's "boundaries" is invariable wrong and I end up moving code around. Plus working primarily in one core bundle makes navigating the code a lot more straightforward.
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.