How do I use namespaces with Zend Framework? - zend-framework

Namespaces are really useful and PHP had no support for them until the recent few releases, AFAIK.
When I'm using Zend Framework, I have to remember long names with underscores - like Zend_Form_Element_Button or Zend_Form_Decorator_HtmlTag and so on.
If I use namespaces, this might be possible, and so much easier:
namespace Zend {
class something {
// ...
}
}
namespace Zend\Form {
class something {
// ...
}
}
namespace Zend\Form\Element {
class Button {
// ...
}
}
And to use it I do this:
use Zend\Form\Element\Button;
$btn1 = new Button();
So my question is, is it trivially possible, given the autoloader system and a lot of meta-class "black magic" that lives inside Zend Framework, to rewrite the structure of the code using namespaces, and then have more sensible class names?
The problem is not the length of the class names - Eclipse/Netbeans/Aptana handle that very well, it is the irritant that long names are.
Tends to get confusing after some time if some classes you use have similar parts in the names.
Since ZF is open source licensed, I don't think Zend would mind a namespaced version of the code, if mere renaming and some re-organization of code can achieve that.

Not trivial, no.
Matthew Weier O'Phinney wrote a blog about some of the issues ZF will have to face if and when they refactor the code to support PHP 5.3 namespacing:
http://weierophinney.net/matthew/archives/181-Migrating-OOP-Libraries-and-Frameworks-to-PHP-5.3.html
Abstract is a reserved word in PHP.
The same goes for interfaces. Consider
this particularly aggregious example:
namespace Zend::View
abstract class Abstract implements Interface
{
// ...
}
We've got two reserved words there: Abstract and Interface.
The Zend Framework is full of classes named Abstract and Interface. They're going to have to make a large number of backward-incompatible refactoring changes to make the ZF code support namespaces.
Also since backslash is a metacharacter in strings, any code that dynamically loads classes based on classname, such as Zend_Db::factory() or Zend_Filter_Input, is unnecessarily difficult to implement, because of the hare-brained decision the PHP core team made, using backslash as the namespace separator.

Related

Enterprise Architect Code Generation: Get tags of interface

I use Enterprise Architect for code generation and I would like to automatically retrieve all tags (in my case Java annotations) of the interfaces that a class realizes. Consider the following example:
From this model, I want to generate a class that looks like this:
#AnnotationOfMyInterface
public class MyClass {
...
}
So I want to add annotations as tags to MyInterface that should be applied to MyClass during code generation. In the UI, tags of implemented interfaces are shown so I was hoping there is a way to get these tags during code generation.
I tried to edit the code generation templates and found macros to get
All interfaces that a class implements: %list="ClassInterface" #separator=", "%
All tags with a given name (of the class that code is being generated for): %classTag:"annotations"%
But unfortunately, I cannot combine these macros, i.e., I cannot pass one interface to the classTag macro so that I can retrieve the tags of that particular interface (and not the one I'm generating code for). Is there a way to get classTags of a specific class / interface?
I also tried to create a separate code generation template and "call" it from the main class code generation template. But inside my template, the classTag macro still only gets the tags of the class.
Thanks to the comments above and especially because of an answer to my question in EA's forum, I was able to setup a little proof of concept achieving what I wanted. I'm answering my question to document my solution in case someone has a similar problem in the future.
After Eve's hint in EA's forum I looked into creating an AddIn for Enterprise Architect to use this AddIn from a code generation template. I started by writing a basic AddIn as explained by #Geert Bellekens in this tutorial. Afterwards I changed the AddIn to fit my needs. This is how I finally got the tagged values (annotations) of the interfaces a class realizes:
First step:
Inside a code generation template, I get all the interfaces a class realizes and pass them to my AddIn:
$interfaces=%list="ClassInterface" #separator=", "%
%EXEC_ADD_IN("MyAddin","getInterfaceTags", $interfaces)%
Second step:
As documented here the repository objects gets passed along with the EXEC_ADD_IN call. I use the repository object and query for all interfaces using the names contained in $interfaces. I can then get the tagged values of each interface element. Simple prototype that achieves this for a single interface:
public Object getInterfaceTags(EA.Repository repo, Object args)
{
String[] interfaceNames = args as String[];
String firstInterfaceName = interfaceNames[0];
EA.Element interfaceElement = repo.GetElementsByQuery("Simple", firstInterfaceName).GetAt(0);
String tag = interfaceElement.TaggedValues.GetAt(0);
return interfaceElement.Name + " has tag value" + tag.Value;
}
I know, there are a couple of shortcomings but this is just a simple proof of concept for an idea that will most likely never be production code.

Issue with extending class in TYPO3

I saw some extension files which are in TYPO3 4.5. (class.tx_ajaxsearch_pi1.php...), looks like this way:
class tx_ajaxsearch_pi1 extends tslib_pibase {
...
if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/ajax_search/pi1/class.tx_ajaxsearch_pi1.php']) {
include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/ajax_search/pi1/class.tx_ajaxsearch_pi1.php']);
}
I am checking this document about XCLASS: http://typo3.org/documentation/document-library/core-documentation/doc_core_api/4.1.0/view/3/8/
Questions:
According to this document: http://typo3.org/documentation/document-library/core-documentation/doc_core_api/4.1.0/view/3/8/
Extending TYPO3s PHP classes is recommended mostly for special needs in individual projects. This is due to the limitation that a class can only be extended once. Thus, if many extensions try to extend the same class, only one of them will succeed and in turn the others will not function correctly.
But why class tslib_pibase can be extended many times by different extension classes?
Is it a good habit to put below codes in every extension scripts? Just in case the extension class needs to be extended in the future?
if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/ajax_search/pi1/class.tx_ajaxsearch_pi1.php']) {
include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/ajax_search/pi1/class.tx_ajaxsearch_pi1.php']);
XCLASS'ing is an approach, when someone substitutes one class with another one. Sounds like inheritance in OOP, but in fact it is different, because you can XCLASS only once, since in TYPO3 global scope one class definition is substituted with another one.
So, i.e. you XCLASS t3lib_db with ux_t3lib_db - that means, taht t3lib_db will never be used in DB processing, but ux_t3lib_db
Sure, your XCLASS can extend the base class, like ux_t3lib_db extends t3lib_db, so it works with inheritance of OOP, but if someone else would like to XCLASS t3lib_db too this will fail simply because TYPO3 will not find t3lib_db in it's scope, because it is already substituted with ux_t3lib_db. So, the only winner will be the one, who XCLASS'ed first.
You can read more here.
But, general note is, that XCLASS'ing is the last option you should try. Use hooks or signals/slots (last works in ExtBase only).
Answering your second question, I can say, that yes, you can do this in 4.5, but no - you shouldn't do that from 6.0.

EF5 Database first model templates (tt) for class generation

I want to make that all my Entities created form an existing database inherits from the same interface.
I suppose this can be done through the templates. And I've seen that ugly .tt file, but there is no help (or I haven't found it).
There are any documentation, examples, ... of the templates?
There are any tips or pre-made templates for common paradigms, for example N-Layer Design or Domain Driven Desing?
Look for "T4 Templates". That will give you introduction to T4 Templates (.tt files).
With a bit of searching you can easily extend this template to your needings. I did this myself already, but with a template from EF4. I don't know if the templates differ.
I made a little helper functions for this:
string Interfaces(EntityType entity)
{
string interfaces = string.Empty;
if (entity.Members.OfType<EdmProperty>().Any(edmProperty => edmProperty.Name == "Guid" && ((PrimitiveType)edmProperty.TypeUsage.EdmType).PrimitiveTypeKind == PrimitiveTypeKind.Guid))
{
interfaces += ", IHasWritableGuid";
}
return interfaces;
}
The part where the template writes the actually entity class (this differs for sure in the new template) is somewhat below "Write EntityType classes." in the EF4 template.
<#=Accessibility.ForType(entity)#>
<#=code.SpaceAfter(code.AbstractOption(entity))#>
partial class
<#=code.Escape(entity)#> :
<#=BaseTypeName(entity, code)#>
<#= Interfaces(entity) #>
Here I just added a call to my interfaces method.
I know this is not the exact answer, but it should give you help with editing the template file yourself. Just bite yourself through it. :)

What is the benefit of using Unity Application Block or DI in general with Entity Framework as in my sample case

In the pseudocode below I have 3 layers: UI, BL, and DL for ASP.NET WebForms app.
Can someone give me some pointers about why would I need to use Dependency Injection
and Unity here? I am using interfaces a lot (mostly for 3rd party components like Mail or File Parsers so I can replace them as needed without changing other layers), but I do not get why I should use interfaces on EF EntityObjects. I can not seem to find one example on the web which would show a practical advantage beyond theoretical unreal cases.
namespace Sample.ASP.NET.UI
{
using Sample.ASP.NET.BusinessLayer;
using Sample.ASP.NET.DataModel;
protected class AspxCodeFile
{
protected Page_Load()
{
GridView.DataSource=BusinesLayer.Products.GetProductsAsList();
}
}
}
namespace Sample.ASP.NET.BusinessLayer
{
using Sample.ASP.NET.DataModel;
protected class Products
{
public static List<Product> GetProductsAsList()
{
EdmxEntities DB=new EdmxEntities();
return DB.Products.ToList<Product>();
}
}
}
namespace Sample.ASP.NET.DataLayer
{
// wrapper namespace for Entity Framework designer
// generated code off SQL Server 2008 database
// where one of the tables is called Products
// and designer created Product EntityObject
// this Product entity is referenced in both
// UI and BL.
}
In your scenario you obviously don't need it. People use dependency injection when they need to inject dependencies and replace them with other implementation - most common reason is automated testing and mocking / faking / stubing dependencies. Another reasons are dynamic behaviors.
In addition to the points Ladislav has made, there are a few others: -
You can use Unity to decorate methods and classes with cross cutting concerns (in Unity these are called behaviours). You can use behaviours anywhere, but I have used this with EF to do things like: -
Automatic creation / save / cleanup of your object contexts
Automatic caching of e.g. reference data
Logging of method call times to find performance bottlenecks on the DAL
Slightly more design related, but using Dependency Inversion Principle you can more loosely couple your system so e.g. your UI does not reference the Business Layer (and potentially decoupled from EF entirely depending on how you're generating your entities).

Need suggestions regarding Interface refactoring

I have inherited a project that has an awkwardly big interface declared (lets call it IDataProvider). There are methods for all aspects of the application bunched up inside the file. Not that it's a huge problem but i'd rather have them split into smaller files with descriptive name. To refactor the interface and break it up in multiple interfaces (let's say IVehicleProvider, IDriverProvider etc...) will require massive code refactoring, because there are a lot of classes that implement the interface. I'm thinking of two other ways of sorting things out: 1) Create multiple files for each individual aspect of the application and make the interface partial or 2) Create multiple interfaces like IVehicleProvider, IDriverProvider and have IDataProvider interface inhertit from them.
Which of the above would you rather do and why? Or if you can think of better way, please tell.
Thanks
This book suggests that interfaces belong, not to the provider, but rather to the client of the interface. That is, that you should define them based on their users rather than the classes that implement them. Applied to your situation, users of IDataProvider each use (probably) only a small subset of the functionality of that big interface. Pick one of those clients. Extract the subset of functionality that it uses into a new interface, and remove that functionality from IDataProvider (but if you want to let IDataProvider extend your new interface to preserve existing behavior, feel free). Repeat until done - and then get rid of IDataProvider.
This is difficult to answer without any tags or information telling us the technology or technologies in which you are working.
Assuming .NET, the initial refactoring should be very minimal.
The classes that implement the original interface already implement it in its entirety.
Once you create the smaller interfaces, you just change:
public class SomeProvider : IAmAHugeInterface { … }
with:
public class SomeProvider : IProvideA, IProvideB, IProvideC, IProvideD { … }
…and your code runs exactly the way it did before, as long as you haven't added or removed any members from what was there to begin with.
From there, you can whittle down the classes on an as-needed or as-encountered basis and remove the extra methods and interfaces from the declaration.
Is it correct that most if not all of the classes which implement this single big interface have lots of methods which either don't do anything or throw exceptions?
If that isn't the case, and you have great big classes with lots of different concerns bundled into it then you will be in for a painful refactoring, but I think handling this refactoring now is the best approach - the alternatives you suggest simply push you into different bad situations, deferring the pain for little gain.
One thing to can do is apply multiple interfaces to a single class (in most languages) so you can just create your new interfaces and replace the single big interface with the multiple smaller ones:
public class BigNastyClass : IBigNastyInterface
{
}
Goes to:
public class BigNastyClass : ISmallerInferface1, ISmallerInterface2 ...
{
}
If you don't have huge classes which implement the entire interface, I would tackle the problem on a class by class basis. For each class which implements this big interface introduce a new specific interface for just that class.
This way you only need to refactor your code base one class at a time.
DriverProvider for example will go from:
public class DriverProvider : IBigNastyInterface
{
}
To:
public class DriverProvider : IDriverProvider
{
}
Now you simply remove all the unused methods that weren't doing anything beyond simply satisfying the big interface, and fix up any methods where DriverProvider's need to be passed in.
I would do the latter. Make the individual, smaller interfaces, and then make the 'big' interface an aggregation of them.
After that, you can refactor the big interface away in the consumers of it as applicable.