Version 4, last updated by fonny at 23 Mar 17:16 UTC
Writing concrete code
Nooku Framework has a lot of code that is intended to be dynamic and generic, in order to do many things automatically across extensions. The code you write for your extensions is not framework level code, so you should try to code as concrete, as literal and as simple as possible (but not one bit simpler).
For example, in Nooku Framework, you might see something like this:
$identifier = clone $this->_identifier;
$identifier->name = KInflector::tableize($identifier->name);
$identifier->path = array('table');
$table = KService::get($identifier);
What does this code do?
- First it makes a clone of the current object's identifier. (An identifier is a string or object that represents an object, for example
com://admin/foo.model.bars). - It takes the name of that identifier and formats it as a table name (eg. ShopProducts becomes
shop_products). - It changes the path (in our case from 'model' to 'table')
- It uses the cloned and modified identifier to get a table object from the service.
Why this complexity?
Because this code is at framework level and it doesn't know anything about the context where it wil be used. This code is generic: it will work in all scenario's, for example in com://admin/foo.model.bar, but also in com://custom/shop.model.products.
Keep it simple
Your life is a lot easier than that of a framework developer: you know exactly what context you are in. When you want something, all you have to do is ask:
$table = KService::get('com://admin/shop.table.products');
If you want the products table object, you simply ask directly for that object. There's no point in writing dynamic code when the result of the code is always going to be the same. This code is also a lot easier to read: you see exactly what the contents of $table is.
In some cases you will need more dynamic code, but you'll know when you get there. Remember the YAGNI-principle: You Ain't Gonna Need It. Don't copy code from Nooku, try to use the API's.
General rule:
- Write your code as simple as possible
- Call objects by their name
- Only add complexity where absolutely needed (YAGNI)
Remember, Nooku Framework is designed to make your life easier, so don't make it harder for yourself!
Examples
A real life example that was posted on the mailing list:
class ComHarbourToolbarButtonHelp extends KToolbarButtonAbstract
{
public function getLink()
{
$option = KRequest::get('get.option', 'cmd');
$view = KInflector::singularize($this->getName());
return 'index.php?option='.$option.'&view='.$view;
}
}
The only intention of this code is create a button that links to index.php?option=com_harbour&view=help. This link is always the same, so there is no point in generating it dynamically (in fact that could cause more issues than it solves). The simple solution:
class ComHarbourToolbarButtonHelp extends KToolbarButtonAbstract
{
public function getLink()
{
return 'index.php?option=com_harbour&view=help';
}
}