I have tried many PHP MVC frameworks and I noticed that in many frameworks you can do things like this:
$this->security->encodeForHTML();
So, basically there is a class Security, which contains a method encodeForHTML(). Isn't this Security class a singleton? Is there a specific name for this kind of "internal" singleton class?
Because there are other classes that are not singletons:
$form = new Form;
In this case, you can create as many forms as you want. I understand the point of this, it clearly doesn't make sense to initialize many security classes, but I am wondering, are there names for these classes (other than singleton and non-singleton)? One guy suggested to use word "plugins" for those classes that can be created and "libraries" for those, which are built in the framework. Does that make sense?
Thanks for your reply!
Current MVC fashion/naming convention calls these Helper Classes/Objects, which is orthogonal to singleton/non-singleton, (helpers often are create as a singleton and/or class with static methods, but they don't have to be)
See Zend Documentation for an example.
A plugin isn't quite the right description. Typically plugins are code/programs written by outside parties to leverage and/or extend functionality within a system. A plugin would be more if the system you were using provided a way for YOU to write a security class and have it automatically instantiated and it's methods available to call, and if your security class could call on System APIs in a standard, non-hack way.
I agree with that 'one guy' you mentioned in your post.
IMO, it really depends on what kind of MVC framework you are using. I haven't tried other frameworks yet, but in CodeIgniter, this falls under two things, models or libraries. Since models are commonly used to handle informations from the database, I would call this 'security' class you mentioned, a library.
Related
I am using my own home grown PHP framework and it is heavily based on components mostly from pear and Zend but lately there are some better components coming up at Composer
As my apps are growing it becomes harder to switch between components, and I am wondering if there is a way I can design my programs differently. In a way that would allow me to use components like the opposite of abstract classes.
I am thinking there should be a way for me to create my own classes, which in turn just hook in to pear or zend and use those classes like as if they wore interfaces or abstract classes. Of course they would be doing the actual work and I would just link to them.
Hypothetically if I have been using pear Config/Lite, which can only work with ini and array files, and now I like to switch to pear config or Zend config to get the benefit of saving the data in a database then there should be an easy way to switch without changing all my code since what they implement is exactly the same thing.
I am asking because I been using pears Net/URL/Mapper, which isn't bad but I found something that would also take care of the dispatching, and is being actively developed. Also I am sure that this kind of situation will come up again and again.
You want to look for something like the facade design pattern, or just use delegation / composition. However beware, using something like a facade can lead to a lot of unneeded complexity as you add layers of abstraction. I recommend you read some php design patterns, especially delegation / composition of objects to get a feel for how that might fit your case.
You should use composition for this IMO. Have the classes in your library expose their own public interface, which the rest of your code depends on. If you ever change the underpinnings of a component from say PEAR to Zend, just ensure all the original public methods still honor the previous version and you should be golden. You can formalize these interfaces with the interface keyword if you wish, but that is beyond the scope of this answer ;)
I'm currently developing a framework which uses an object of a Core class (this class has huge functionality & makes the framework working). The framework follows MVC architecture & has loosely coupled Model, Control, View classes. Theses classes need a reference to the Core class heavily. What I've done so far is: creating single object of the Core class & referencing to it by PHP keyword global in Model, Control, View classes.
I don't like using this approach mainly because:
This way is not true object oriented way in my sense
The IDE (netbeans) can't provide documentation to the object of the Core class - a pain for developers who will be using this framework.
I'm really worried about performance issues - have no idea whether global is slower or whatever.
I've searched & did not find any information regarding performance issue. I've also searched stackoverflow & found Does using global create any overhead? & The advantage / disadvantage between global variables and function parameters in PHP? etc links but they don't contain much information. Right now my main concern is performance, so please help.
I must agree with NevilleK, that you Core` class sounds line an God Object antipattern.
And for anyone dumb enough to suggest use of singletons/registries i would suggest to do a little research on the subject. They create the same global state as your classical global variables.
Global state is not so much matter of performance ( though in php it has some minor impact ), but it created untestable and tightly coupled code.
You really should look into the Dependency Injection. That might show you another way , which does not require to have such a Core class in your code.
Some additional videos for you:
Global State and Singletons
Don't Look For Things!
Advanced OO Patterns
Cake is a Lie
Clean Code: Arguments
I've solved a similar problem in Agile Toolkit by creating a different pattern for adding object and using it system-wide. This passes a property to a newly created objects called "api" which always references Application class.
Application class is not really a God class but it delegates all sorts of functionality to system controllers, pages etc. This screencast explains how the very basic objects are structured, it might be something you are also looking for:
http://www.youtube.com/watch?v=bUNEHqYVOYs
Firstly, whilst you are concerned with performance, you may want to read http://en.wikipedia.org/wiki/God_object first - your "core" class sounds like a "God object", which is a fairly well-established anti pattern.
In terms of performance - the best way to find out is to test it. If you're writing a framework, I'm assuming you're writing unit tests to validate it's behaviour; it's not hard to extend that unit testing to include simple performance metrics. You might also invest in test scripts using JMeter or similar to exercise a "reference implementation" of a few pages built using the framework. You'll get far better information on your specific situation from doing this than by trying to optimize the design based on Stack Overflow's collective knowledge of the general way things work.
In general, I'd say that having a global class shouldn't impact performance too much, as long as it isn't doing much work. Simply loading the class into memory, parsing it, etc. does have a performance impact - but it's not likely to be measurably slower than any other routes you might take.
If, however, your "core" class does lots of initialization logic when it's accessed by the page, it's obviously going to impact performance.
I'm following a tutorial which I think is written by someone who doesn't know what he's doing (already caught 2 obvious mistakes and the rest of code is messy). But I don't want to discredit the guy completely, so I'm asking here about something else that I don't understand.
First of all, I will send 100 brownie points,
my 2 pets, and a box of chocolate to
whoever can explain to me what is
going on with this code.
He's using module-based architecture. Module name is frontmodule. Module has MVC. And module has an internal library of its own.
/modules/
/frontmodule/
/models/
/views/
/controllers/ -- the /module controller is here (undestandable)
/library/
/Controller/ -- the /module/library controller is here (why?!)
/Action/
First comes the confusing part. Why each module has an internal library, and why that intenal library has its own controllers and actions. Is this a best practice? I'm thinking this library could be moved to a plugin that the module can use. Not sure..
Now comes the interesting part.... in addition to each module having its own internal library, there's also a Common library shared by all modules (see it below at the same folder level as /modules) and that Common library also has its own controllers and actions (just like each internal libraries have their own controllers and actions)
/modules
/library/
/Common/
/Controller/ -- the /common/library controller is here (why?!)
/Action/
/Helper/
/Plugin/
So we have 3 controllers:
the module controller
the module internal library's controller
the common library's controller
Now here's the insane part that I think is over-complicating life
He says: A module controller extends the
module’s library parent controller
which also extends the Common library
controller.
class IndexController
extends Frontoffice_Library_Controller_Action_Abstract { ... }
abstract class Frontoffice_Library_Controller_Action_Abstract
extends Custom_Controller_Action_Abstract { ... }
So I guess:
the module controller = IndexController
the module internal library's controller = Frontoffice_Library_Controller_Action_Abstract
the common library's controller = Custom_Controller_Action_Abstract
where module controller extends module internal library's controller
and module internal library's controller extends common library's controller
Has anyone seen anything like this before? My guess is that this code won't be easy to maintain, but maybe those more experienced with zend can tell me what this guy is trying to achieve. The app structure is a little too messy. I think he's abusing MVC instead of using it to simplifying the app and its maintainability.
The great thing about Zend Framework is that it is use-at-will which means you can use a single component or you can use them all. Most components are also very flexible either via configuration or extension (inheritance or composition, with ZF favoring the latter).
Zend Framework MVC is extremely flexible...even to the point where many have accused it of being over-engineered or bloated itself. This is subjective.
Sure, you probably won't want to use Zend Framework for a simple contact form; however, there is nothing stopping you from utilizing just Zend_Mail and Zend_Form without Zend MVC/Application. With flexibility in mind, there is currently no single methodology which is touted as the best in terms of organizing an application into modules. This is a task best left up to the implementer.
This brings us to the tutorial at hand. The tutorial writer has come up with a strategy for re-use. This is a good thing; however, there are some flaws with his approach.
A library per module.
This is not necessarily bad; however, it is in most cases not necessary. Lets explore what options we have just in case such a structure is needed for some reason.
a. Build a general library (you most likely already do this) namespaced (pseudo if < 5.3 or actual namespaces if >= 5.3).
b. Utilize the intrinsic "Resource Autoloader"
http://framework.zend.com/manual/en/zend.loader.autoloader-resource.html
NOTE: I personally haven't used the resource autoloading much. The one time that I did use it, I found that I could have just moved those items to my library. That being said, there are uses for this. It seems to shine when you expect to mix and match modules across projects or for distribution. ZF2 will address this in a less hacky way IMHO.
Base controllers for re-use.
Again, reuse is great; however, Zend Framework provides better alternatives to sub-classing (inheritance) controllers. First, here are some reasons NOT to use controller inheritance:
a. Keeping things DRY is defeated when you have multiple modules that differ enough to need a base-class per module but functionality is copied/pasted across each module's base controller class.
b. It becomes hard to manage inherited properties as it is harder to visualize what inherited functionality is being utilized by each controller/action
c. With PHP allowing only single class inheritance, you blow your one chance at inheritance here -- use this only if there are no other options left
Alternatives:
a. Front-Controller Plug-ins
Use these when the functionality/logic needs to run on every request regardless of module/controller/action
b. Action helpers
As mentioned by the ZF project lead, "They're a built-in mechanism in Zend Framework to allow you to extend your action controllers in a way that uses composition instead of inheritance."
There isn't anything that you can do in a controller that you can't do via an action helper.
Use these when the functionality needs to happen on a per controller and/or action basis.
So, was the example in the tutorial over-engineered? Not necessarily; however, it is certainly a candidate for incorrectly-engineered as it relates to best practices and provisions given by Zend Framework.
I need to digress for a moment and discuss the terms over-engineered and bloated for just a moment
When someone tells you that something is over-engineered and/or bloated without stating a context please take it with a grain of salt.
The Wikipedia article - http://en.wikipedia.org/wiki/Overengineering reads in part "...when a product is more robust or complicated than necessary for its application...".
So, when referring to something as Over-engineered/bloated one should be careful to qualify the context or application at hand. Blanket statements should be taken with a grain of salt and in most cases, not taken at all. This is akin to saying something like "I'd never use a 'Circular Saw' for woodworking since it has way too many features and those features confuse me". Sure, this tool may be over-kill for small home/side projects; however, since it is super flexible you will be happy you have this tool when you find yourself in situations where you never thought you'd find yourself.
Yes, most web frameworks are over-kill for a simple CRUD application such as a contact page or even a simple blogging application. It is unfortunate that most web frameworks use the blog example as their introductory example - go figure.
Extra Info:
If you wanted to switch layouts based on the module/controller/action, you could write a Front-Controller Plug-in. Just call "Zend_Layout::startMvc" and pass it a layout name and a path.
Switching the actual view script based on the Accept header (or URL parameter or X-HTTP-METHOD-OVERRIDE header) can be done with the context switch action helper (intrinsic to Zend Framework) - http://framework.zend.com/manual/en/zend.controller.actionhelpers.html
Feel free to pass a model instance to an action helper. You can also configure your action helpers with configuration from the bootstrap. This way, there is no need to store things in the global registry which is just a glorified global variable. This is a hidden dependency that you don't need. For the best re-use, you can create your own custom plug-in resources by extending Zend_Application_Resource_ResourceAbstract - http://framework.zend.com/manual/en/zend.application.core-functionality.html#zend.application.core-functionality.resource-resourceabstract
This is insane. You're making web pages, right? This isn't hard. I'd say the stuff you posted is the very definition of overengineering:
http://en.wikipedia.org/wiki/Overengineering
Not insane at all. Perhaps badly or overly engineered, but it could be a useful setup.
It's just two "extra" levels of inheritance, which in some cases might make perfect sense.
properties or methods that should be available in every controller in the system go in the "common library controller".
properties or methods that should be
available in every controller in a
particular module go in the "module
internal library's controller"-
properties or methods required by a
single, concrete controller, live in
that concrete controller.
But generally, this suggests packing an awful lot of logic into the controllers, which is generally bad design.
In this way, you can have logic applied to:
a) a particular controller
b) all controllers in one module
c) all application controllers
I've been using the CodeIgniter framework, however after learning Java and awesome features like Interfaces, Abstract classes, packages, and that PHP 5 also supports most of these features, I'm ready to graduate and build a real OO framework in PHP which uses all of these features (including namespaces), so I can build much more elegant designs.
What I'm thinking of is that rather than everything in the system sharing a single $this-> object like its done in CodeIgniter, e.g:
$this->load->model('box');
$this->box->something();
You would do the following to load the Box model and to call its something() method.
$box = new Framework\Models\Box();
$box->something();
Or the following
abstract class BaseController
{
public function getModel($name)
{
$model = new Framework\Models\$model(); //Is this valid code?
return $model;
}
}
class MyController extends BaseController
{
public function index()
{
$box = $this->getModel('box');
$box->something();
}
}
Are there any suggestions/pointers for building this, such as which minimum system classes I would need for the framework, what namespaces I should have, or any other features?
One thing I've noticed is that a framework is usually built for a specific purpose. Generic frameworks (like CodeIgniter) are good for smaller sites and getting things up and running quickly. However once you have specific things, which fall outside of the generic framework building your own does become a reality.
The only thing I would suggest is to be consistent. That is relentlessly consistent. If you decide to name things in camelCase then don't deviate from that. Or if you decide to use the NounVerb convention of naming methods i.e. spaceJump then don't switch to jumpSpace even if it 'sounds' better at the time.
Choose how you'll accept parameters and be consistent on that. Will you accept only parameters or associative arrays of parameters? Choose and stick with it.
I would also not over-engineer before you've written anything. The consistency thing will take you pretty far before you'll need to refactor... but I wouldn't be afraid to do that as well. (A unit test or two should ease those fears).
Yup, there's usually no right or wrong way to do things as long as you're consistent. Did I mention...
Be Consistent!
A lot of experience is needed to build a technical framework (no offense) and there are already 1'000's of CMS/basic objects (session management, ORM, etc.) framworks/libraries.
Instead of wasting precious time (no offense again), you better have to:
Evaluate and select the framework that better suits your needs (some have a really good OO architecture).
Learn will using this good framework.
Build your own OO business/application framework. (This is where you can learn, differentiate and create value).
You can build your own but why not make use of the vast libraries included with frameworks available and if required extend their functionality.
Why don't you take a look at the Zend framework.
It's fairly quick to get started and includes a lot of useful libraries and classes as standard. It's good for personal projects if your just looking to gain more experience with OOP.
http://framework.zend.com/
I would look at Kohana. It came out of CodeIgnitor, and loading Models etc is done just the way you proposed.
Check out their core features, many of which relate directly to your question (I've highlighted those):
How is Kohana Different?
Although Kohana reuses many common design patterns and concepts, there are some things that make Kohana stand out:
Community, not company, driven. Kohana development is driven by a team of dedicated people that need a framework for fast, powerful solutions.
Strict PHP 5 OOP. Offers many benefits: visibility protection, automatic class loading, overloading, interfaces, abstracts, and singletons.
Extremely lightweight. Kohana has no dependencies on PECL extensions or PEAR libraries. Large, monolithic libraries are avoided in favor of optimized solutions.
GET, POST, COOKIE, and SESSION arrays all work as expected. Kohana does not limit your access to global data, but offers filtering and XSS protection.
True auto-loading of classes. True on-demand loading of classes, as they are requested in your application.
No namespace conflicts. All classes are suffixed to allow similar names between components, for a more coherent API.
Cascading resources offer unparalleled extensibility. Almost every part of Kohana can be overloaded or extended without editing core system files. Modules allow multi-file plugins to be added to your application, transparently.
Library drivers and API consistency. Libraries can use different "drivers" to handle different external APIs transparently. For example, multiple session storage options are available (database, cookie, and native), but the same interface is used for all of them. This allows new drivers to be developed for existing libraries, which keeps the API consistent and transparent.
Powerful event handler. Observer-style event handlers allow for extreme levels of customization potential.
Rapid development cycle. Rapid development results in faster response to user bugs and requests.
I'm building my personal CMS and need your advice organizing core functions and classes.
I have folders:
/shared
/classes
DB.php
Session.php
Config.php
...
/libraries
Arrays.php
DateTime.php
Email.php
...
The files in 'classes' folder contains core classes (one class per file).
Now the question is about /libraries/ - they contain functions that may be used in any class, and sometimes they use some other function from another library, and sometimes they need to access some core class.
Should i just write them as functions, or make them static and wrap in some class?
Basically i need them everywhere, but keep them organized.
Should i just write them as functions,
or make them static and wrap in some
class? Basically i need them
everywhere, but keep them organized.
Have you looked into namespaces yet? Wrapping all of your functions into a namespace would probably be your best bet.
My suggestion is to first think through about the architectural goals of your CMS. Sure, it's going to be 100% yours, but that doesn't mean you wont suffer from not begin sure whats hooked where and how, what this does and how do I get that from here.
That's why I definitely wouldn't suggest you have libraries calling libraries. From my point of view, none of your classes should be dependent on anything else except for the first few core classes in your application flow since you'd like to distributed the work in some other single purposed self-contained classes. You should aim for singularity and atomicity with your core classes.
I don't know what your architectural pattern will be (I'll presume it's going to be MVC, HMVC or PAC), but I think it's best you first define a few core classes [/core] that will lay the foundations on initializing the application by instancing some libraries [/libraries] that are required for parsing the incoming requests request and doing some default tasks before initializing the requested controller [/controllers].
Libraries should have a single purpose. The session handling library should solely handle sessions, the routing library routing, etc. Initially you can create your base controller and base model and put it in [/core] and have controllers [/controllers] and models [/models] extend your base controller and model from [/core].
As always, the less coupled your components are the better. A good solution will be lightweight, small and extensive in it's purpose. It helps if you change any design ideas in the future that you can simply change the core classes and have a huge impact on the whole application without having to make any further changes in other places.