Zend Model access in singleton class - best approach - zend-framework

I'm looking for best pattern/approach to access one table data in singleton class (in ZF 1.x). In details:
I have one singleton class (just like Zend_Date for example) that make for me some basic abstract stuff very detached from application reality.
In this class, in two points, I need to access to one db table and I need to make some basic operation on it.
It's not a problem to use my regular ZF models class inside functions of this singleton. It works fine. Now it look like:
class My_ZF_Singleton
{
...
public function someFunctionInMySingleton()
{
...
$oModel = new Model_My_Model_Form_ZF_Application();
$oModel->letsDoSomeStuffWithDb();
...
}
...
}
But I feel in my bones that it's not a very good solution, not so glamour as I would like to be. It make my singleton class more attached to application then it should be. I would like to use some other pattern to access this db data then application model class. I would be very thankfull for any clue or better solution - it's not a "hey I'm stuck probem" or "hey I've got an error" - I'm just looking for better solution.

Not sure I quite understand your question or want the point might be, but I'll try.
In ZF1 the database adapter is typically a singleton already. Multiple databases maybe connected to but each will require a unique identification. Typical access to the default adapter setup in the application.ini or Bootstrap.php:
$adapter = Zend_Db_Table::getDefaultAdapter();
a common way to provide access to a single database table and give access to the Zend_Db_Table api is to build a DbTable model:
class Application_Model_DbTable_TableName extends Zend_DbTable_Abstract
{
protected $_name = 'Table_Name' //required if classname does not match table name
protected $_primary = 'primary_key_column_name'//optional, use if primary key is not 'id'
}
You can treat this class as an instance of the default database adapter for a single table (works really well in a mapper). You can also add functions to this class to override or add to the default Zend_Db_Table api.
I hope this at least comes close.

Related

Entity Framework & WPF Application Design Guidance

Entity Framework Layer Guidance
I'm in the design stage of a WPF business application. The first stage of this application will be a WPF/Desktop application. Later iterations may include a browser based mini version.
I envision creating a dll or 2 that contain the domain model & dbcontext that all applications(Desktop or Browser) will use.
My intention is to ride or die with EF. I'm not worried about using DI/Repository patterns etc for flexibility. The benefits of using them don't outweigh the added complexity in my opinion for this project. My plan is to use a model, and a derived dbcontext.
Having said that, I'm looking for input on where to put certain types of method code.
An example will hopefully make my question more clear:
Let's say I have the following two entities..
Entity: Employee
Entity: PermissionToken
Inside of these two entities I have a ManyToMany relationship resulting in me creating another entity for the relationship:
EmployeesPermissionTokens
For clarity, the PermissionToken Entity's Primary Key is an Enum representing the permission..
In the application, lets say the current user is Administering Employees and wants to grant a permission to an Employee.
In the app, I could certainly code this as:
var e = dbcontext.Employees.Find(1);
var pt = new PermissionToken
{
PermissionID=PermissionTypeEnum.DELETEUSER";
...
}
e.PermissionTokens.Add(pt)
But it seems to me that it would be more convenient to wrap that code in a method so that one line of code could perform those actions from whatever application chooses to do so. Where would a method like that live in all of this?
I've thought about adding a static method to the EF Entity:
In The employee class:
public static void GrantPermission(PermissionToken token)
{
e.PermissionTokens.Add(token);
}
Going further, what would be really convenient for the app would be the ability to write a line like this:
Permissions.GrantToEmployee(EmployeeID employeeId, PermissionTypeEnum
permissionId);
Of course that means that the method would have to be able to access the DbContext to grab the Employee Object and the PermissionObject by ID to do its work. I really want to avoid my entities knowing about/calling DbContext because I feel long term the entities get stuffed full of dbcontext code which in my opinion shouldn't even be in the Model classes.
So Where would a method like this go?
My gut tells me to put these sorts of code in my derived DbContext since in order to do these sorts of things, the method is going to need access to a DbContext anyway.
Does this make sense, or am I missing something? I hate to write oodles of code and then figure out 3 months later that I went down the wrong road to start with. Where should these types of methods live? I know there is probably a purist answer to this, but I'm looking for a clean, real world solution.
First of all you are making a good decision to not abstract EF behind a repository.
With the EF Context you have a class supporting the Unit Of Work pattern which is handling your data access needs.No need to wrap it up in repository.
However this does not mean you should call the Context directly from your controller or viewmodel.
You could indeed just extend the DbContext however I suggest to use services to mediate between your controllers/view models and your dbcontext.
If e.g. in your controller you are handling a user request (e.g. the user has clicked a button) then your controller should call a service to archive what ever "Use Case" is behind the button.
In your case this could be a PermissionService, the PermissionService would be the storage for all operations concerning permission.
public class PermissionService
{
PermissionService(DbContext context)
{
}
public bool AddPermission(Employee e, PermissionType type) { }
public bool RemovePermission(Employee e, PermissionType type) {}
}
Your service ofcourse needs access to the DbContext.
It makes sense to use DI here and register the DbContext with a DI Container.
Thus the context will be injected into all your services. This is pretty straight forward and I do not see any extra complexity here.
However, if you don't want to do this you can simply new up up the Db Context inside your services. Of course this is harder / impossible to mock for testing.

Zend - Design Pattern DataMapper & Table Gateway

This is directly out of the Zend Quick Start guide. My question is: why would you need the setDbTable() method when the getDbTable() method assigns a default Zend_Db_Table object? If you know this mapper uses a particular table, why even offer the possibility of potentially using the "wrong" table via setDbTable()? What flexibility do you gain by being able to set the table if the rest of the code (find(), fetchAll() etc.) is specific to Guestbook?
class Application_Model_GuestbookMapper
{
protected $_dbTable;
public function setDbTable($dbTable)
{
if (is_string($dbTable)) {
$dbTable = new $dbTable();
}
if (!$dbTable instanceof Zend_Db_Table_Abstract) {
throw new Exception('Invalid table data gateway provided');
}
$this->_dbTable = $dbTable;
return $this;
}
public function getDbTable()
{
if (null === $this->_dbTable) {
$this->setDbTable('Application_Model_DbTable_Guestbook');
}
return $this->_dbTable;
}
... GUESTBOOK SPECIFIC CODE ...
}
class Application_Model_DbTable_Guestbook extends Zend_Db_Table_Abstract
{
protected $_name = 'guestbook_table';
}
Phil is correct, this is known as lazy-loading design pattern. I just implemented this pattern in a recent project, because of these benefits:
When I call on getMember() method, I will get a return value, regardless if it has been set before or not. This is great for method chaining: $this->getCar()->getTires()->getSize();
This pattern offers flexibility in that outside calling code is still able to set member values: $myClass->setCar(new Car());
-- EDIT --
Use caution when implementing the lazy-loading design pattern. If your objects are not properly hydrated, a query will be issued for every piece of data which is NOT available. The best thing to do is tail your db query log, during the dev phase, to ensure the number and type of queries are what you expect. A project I was working on was issuing over 27 queries for a "detail" page, and I had no idea until I saw the queries.
This method is called lazy-loading. It allows a property to remain null until requested unless it is set earlier.
One use for setDbTable() would be testing. This way you could set a mock DB table or something like that.
One addition: if setDbTable() is solely for lazy-loading, wouldn't it make more sense to make it private? That way it will avoid accidental assignment and to wrong table as originally mentioned by Sam.
Should we be compromising the design for the sake of testability?

EF Codefirst, One class, multiple tables with discriminator

I doing a little investigation and I am wondering if the following is possible.
I am looking to create a BaseEntityWithDetails class that I can reuse for any type that I would like to have extendable. For example
public abstract class EntityDetail
{
}
This class is used to persist a key and value for the entity.
"Products" would be extended by doing the following...
public class ProductDetail : EntityDetail
{
}
public class Product : BaseEntityWithDetails<ProductDetail>
{
}
The base class "BaseEntityWithDetails" will provide some helper methods for setting and getting. What do you think?
What is the most effective way of mapping this with EF CodeFirst while being super easy to allow another type implement an DetailsEntityTypeConfiguration like the following
public class ProductMap : DetailsEntityTypeConfiguration<Product, ProductDetail>
{
}
Thanks in advance!
I would like to quote someone really smart on this: Reuse is a fallacy. Don't bother doing stuff like this because it will only make your design more obfuscated and complex. Save your inheritance to the entities in your domain which really share the same behavior, don't do this type of assumptions up front.
As a side note: You can map this as a table per type if you put your "EntityDetail" into your database, but as I said before, this is just not a good idea.

When are object interfaces useful in PHP? [duplicate]

This question already has answers here:
What is the point of interfaces in PHP?
(15 answers)
Closed 8 years ago.
From php.net:
Object interfaces allow you to create code which specifies which methods
a class must implement, without having to define how these methods are handled.
Why should I need to do that? Could it be a kind of 'documentation'?
When I'm thinking about a class I have to implement, I know exactly which methods I should code.
What are some situations where interfacing a class is a "best practice"?
Short answer: uniform interfaces and polymorphism.
Longer answer: you can obviously just create a class that does everything and indeed you'd know what methods to write. The problem you have with using just concrete classes, however, is your lack of ability to change. Say you have a class that stores your users into a MySQL database, let's call it a UserRepository. Imagine the following code:
<?php
class UserRepositoryMysql {
public function save( User $user ) {
// save the user.
}
}
class Client {
public function __construct( UserRepositoryMysql $repos ) {
$this->repos = $repos;
}
public function save( User $user ) {
$this->repos->save( $user );
}
}
Now, this is all good, as it would actually work, and save the User to the database. But imagine your application will become populair, and soon, there is a question to support PostgreSQL as well. You'll have to write a UserRepositoryPostgresql class, and pass that along instead of UserRepositoryMysql. Now, you've typehinted on UserRepositoryMysql, plus you're not certain both repositories use the same methods. As an aside, there is little documentation for a potential new developer on how to implement his own storage.
When you rewrite the Client class to be dependent upon an interface, instead of a concrete class, you'll have an option to "swap them out". This is why interfaces are useful, obviously, when applied correctly.
First off, my php object coding is way behind my .net coding, however, the principles are the same. the advantages of using interfaces in your classes are many fold. Take for example the case where you need to return data from a search routine. this search routine may have to work across many different classes with completely different data structures. In 'normal' coding, this would be a nightmare trying to marry up the variety of different return values.
By implementing interfaces, you add a responsibility to the clsses that use them to produce a uniform set of data, no matter how disparate they may be. Another example would be the case where you are pulling data from different 'providers' (for example xml, json, csv etc, etc). By implementing an interface on each class type, you open up the possibilities to extend your data feeds painlessly by adding new classes that implement the interface, rather than having a mash-up of switch statements attempting to figure out what your intentions are.
In a word, think of an interface as being a 'contract' that the class 'must' honour. lnowing that means that you can code with confidence for that given scenario with only the implementation detail varying.
Hope this helps.
[edit] - see this example on SO for a fairly simple explanation:
An interface is a concept in Object Oriented programming that enables polymorphism. Basically an interface is like a contract, that by which classes that implement it agree to provide certain functionality so that they can be used the same way other classes that use the interface
purpose of interface in classes
The first case that comes to my mind is when you have a class that uses certain methods of another class. You don't care how this second class works, but expects it to have particular methods.
Example:
interface IB {
public function foo();
}
class B implements IB {
public function foo() {
echo "foo";
}
}
class A {
private $b;
public function __construct( IB $b ) {
$this->b = $b;
}
public function bar() {
$this->b->foo();
}
}
$a = new A( new B() );
$a->bar(); // echos foo
Now you can easily use different object passed to the instance of class A:
class C implements IB {
public function foo() {
echo "baz";
}
}
$a = new A( new C() );
$a->bar(); // echos baz
Please notice that the same bar method is called.
You can achieve similar results using inheritance, but as PHP does not support multiple inheritance, interfaces are better - class can implement more than one interface.
You can review one of PHP design patterns - Strategy.
Say you're creating a database abstraction layer. You provide one DAL object that provides generic methods for interfacing with a database and adapter classes that translate these methods into specific commands for specific databases. These adapters themselves need to have a generic interface, so the DAL object can talk to them in a standardized way.
You can specify the interface the adapters need to have using an Interface. Of course you can simply write some documentation that specifies what methods an adapter needs to have, but writing it in code enables PHP to enforce this interface for you. It enables PHP to throw helpful error messages before a single line of code is executed. Otherwise missing methods could only be found during runtime and only if you actually try to call them, which makes debugging a lot harder and code much more unreliable.

Can I set the Database adapter to use permanently from within a Zend_Db_Table_Abstract Class?

I have 2 databases that my site uses including a central user database that relates to other site-specific databases.
Sometimes it is adequate to call new User(array('db'=>'adapter1')); (but never convenient); other times, though, such as when declaring relationships between tables on different databases, there is no way to do this.
Does anyone know a way to specify which database adapter to use from within the Zend_Db_Table_Abstract class?
Thanks!
Getting back to this pretty late, but none of the answers here quite did it for me. A select few of my database models needed to use 'tdb' and the following code was added to each of those classes to have that happen automatically:
protected function _setupDatabaseAdapter()
{
$this->_db = Zend_Registry::get('tdb');
parent::_setupDatabaseAdapter();
}
I thank you all for your suggestions along the way!
Zend_Db_Table_Abstract provides a static method to set the default database adapter. Do this as follows:
Zend_Db_Table_Abstract::setDefaultAdapter($adapter);
Now, all your Table objects will use your adapter by default.
Note: the online docs sometimes don't make this obvious, so your second best place to check is in the API here: http://framework.zend.com/apidoc/core/
You could set the class variable $_db to the correct adapter in the constructor.
global $adapter1; //There are better ways than using a global variable
$this->_db = $adapter1;
Assuming the adapter object can be referenced in the constructor. That doesn't seem to portable, but I believe it would work.
The init function can be used, it is not used in Zend_Db_Adapter_Abstract, can be used in your class to setup whatever needs to be done. _setAdapter accepts a string naming a Registry Key.
public function init()
{
$this->_setAdapter('tdb');
}