My Question:What are some good examples of design patterns used in CakePHP?
Why Use CakePHP As My Context
I've been using CakePHP for about a year so I think it's easier for me to think in that context. CakePHP is also rich in design pattern use (I'm confident of that)--I just don't know what patterns are being used other than a few obvious ones.
Example Books I've been Reading On the Subject:
I'm reading the following books which all cover design patterns to one extent or another; unfortunately they mostly use Java and C++ code examples which makes it harder for me to get a grip on the design patterns on a practical level (I'm a PHP developer so its hard for me to absorb it):
"Patterns of Enterprise Application Architecture", by Martin Fowler
"Head First Design Patterns", by Gang of Four (Eric Freeman, Elisabeth Freeman, Kathy Sierra & Bert Bates) (2004)
"Design Patterns: Elements of Resuable Object Oriented Software)", by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides)
Examples of Patterns I Can Observe in CakePHP
-I'm guessing the config file uses something akin to the factory pattern
-maybe $this->params is using something related to the observer pattern? I'm not sure on that...
-MVC (obvious! since Cake PHP uses the MVC file structure)
-ORM (another very obvious one)
-Maybe the HTML helper is using the decorator pattern?
Summary
I don't expect anyone to go down the line and identify all the patterns used in CakePHP--I'm just looking for a few examples of design patterns that should be obvious that I'm missing.
One that comes to mind is the concept of mixins. Not exactly a pattern but actually a language feature available in some languages (ie. modules in Ruby) but not in others (ie. Java). It will be coming to PHP when 5.4 goes stable and we get traits, but CakePHP's model behaviours are a good example of mimicking this kind of multiple inheritance where it normally isn't possible.
class Post extends AppModel { // we can only inherit from one class
public $actsAs = array('This', 'That', 'Other'); // but we can do this instead
}
Software design patterns (like a RoR):
Convention over configuration: all configuration files from Configure
Model-View-Controller: folders: Model, Controller, View, etc
ActiveRecord, Association Data Mapping: database mapping
Front Controller: main entry point (index.php)
Found in the comments:
Creational patterns:
Singleton -- find by "getInstance, singleton"
Factory -- find by "factory"
Builder -- find by "builder"
Structural patterns:
Adapter -- find by "adapter"
Front controller (.htaccess, include)
Behavioral patterns:
Strategy -- find by "strategy"
View:
Two-step-view pattern -- "two-step-view"
Related
Recommendations I understood in Java (which has a lot of restrictions, # least for me), even with hibernate was to have separated layers
Entities like persons, children, users, etc...
DAO entities linked to database
Service providing entities and functionalities, where I'll do the SQL
WebService providing an interface over needs
As I'm starting with Eiffel and store, I'm facing some difficulties I face since ever in programming (hoping there's somebody in this earth who has not the same problem) I always want to generalize things more than necessary. Every time I do a copy-paste, I refactor and look for a solution which makes me able to write it one time... which takes time and time on the delivery of the software, but for me adds more quality and flexibility to the software. I'm actually working alone in a company where I'm going to be the lead developer and if the future wants we'll be more developers. The goal is to develop a platform of services in Eiffel, postgresql-odbc, and an Angular-web front-end.
I'd like to have the more generic pattern to be able to manage entities in the future with typical situations as:
Database entities
Relationships
one_to_one
one_to_many
many_to_one
many_to_many
# The point I'm now, I'm about to develop an architecture which ideally for me has:
DB_ENTITY which as relations: BAG[RELATIONSHIP[P,S]] where P=Primary and S=Secondary
Primary is P->DB_ENTITY when ONE and BAG[P] when MANY
A COMPANY on my design will inherit from DB_ENTITY and add relationships as a BRANCH. So I was thinking having in my COMPANY class branches: RELATIONSHIP[like Current, BRANCH]
The relationship classes would help me to create the CRUD SQL statements into the "service" layer in a more abstract manner.
when I try something more lightweight I find restrictions in the pattern where I have to repeat operations... thats a bit my difficulty
Do you think of any disadvantages of such model I'm creating out of the first shot of development?
Quenio dos Santos not wanting to create an account on stackexchange, I'll quote its answer which could be useful for others
I recommend the book:
https://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software-ebook/dp/B00794TAUG/ref=sr_1_2?s=digital-text&ie=UTF8&qid=1540350158&sr=1-2&keywords=domain+driven+design&dpID=51OWGtzQLLL&preST=_SY445_QL70_&dpSrc=srch
Not just because of the Repository pattern.
You should be able to implement reusable, abstract classes out of the
repository pattern if you want to get away from repetitive code. In
Java, MyBatis is a framework that helps with that. I really don’t know
if there is anything equivalent in Eiffel. I’m also a new Eiffel
developer.
Some pros-and-cons of the Repository pattern:
You define the SQL yourself. Some see it as a cons, but some see it as a pros, because you have clear understanding of the mapping from
the database to your classes, and it allows you to optimize your
queries, and join several tables into a single class, or smaller
number of classes, when approriate in your context.
More freedom on how you define your domain model. It can be quite different from the schema of your database. Your classes don’t have to
be just a set of anemic attribute holders of the tables in your
database, but they can have behavior and be useful and expressive in a
setting completely independent from your database.
ORM frameworks, like Hibernate, are sometimes hard-to-use for a new developer not very familiar with them. With the repository pattern,
because the mapping is so clear and available in your own code, it
tends to be easier to understand and debug.
You can also have different implementations of your repositories for different technologies, such as NoSQL databases. With ORM frameworks,
you tend to be stuck with a relational database, unless you rework
quite a bit of your dependencies on the ORM framework. It is easier to
encapsulate the data store technology behind repositories, and keep a
clean separation between your domain model and your database.
I’d say those are the main points. Having said that, these are very
general guidelines. I don’t have any experience with data persistent
in Eiffel, so I couldn’t say what are the best practices for Eiffel
developers. But I have a gut feeling that the repository pattern fits
well Eiffel because the original goal of the language was to build
more abstract, domain-rich class libraries, which is the purpose
behind the repository pattern. (By the way, I’m calling it a pattern,
but I’m not sure the author calls it that. The author would probably
call aggregates, entities and repositories, all kinds of classes used
in domain-driven design, all together a pattern.)
In the context of test automation I'm using a simple version of the Page Object Pattern and facing the problem of having redundance in my code.
That said, in a class I'm having multiple methods which basically do the same thing but just return different page objects:
class Checkout {
gotoNextPageExpectCreditCardPage() {
clickSubmitButton();
return new CreditCardPage();
};
gotoNextPageExpectPaypalPage() {
clickSubmitButton();
return new PaypalPage();
};
...
gotoNextPageExpectErrorPage() {
clickSubmitButton();
return new ErrorPage();
};
}
I've done some research and thought of some design patterns like State Pattern, Template Method, Chain-of-responsibility, but am also thinking these might be overkill and that I'll have to do a huge refactoring.
Does anyone come up with a simpler solution?
PS.: I'm using node.js
PageObjectModel has its pros and cons, as any other pattern. Maybe you need to consider again what is your case and why you are using it. In most tutorials you will find, it is very easy and simple to implement, but those solve and demonstrate toy problems, not real life ones. I use POM only where the test framework API supports it by design, for example pywinauto. The concepts here allows you to chain your elements like so:
app.UntitledNotepad.Edit
And there is no point of repeating such screen structure all over your codebase, just put the UI details in a POM and provide the element when an interaction is needed.
notepad.EditInput.type_keys("pywinauto Works!", with_spaces = True)
As you can see - this is very far away, from Selenium and Web automation. But,
there are plenty of other patterns you can look for:
Object repository is very helpful when it comes to UI test scripts maintainability, I have used it in numerous big projects with great success (e.g. mSOA platform with more than 40 web sites)
Screenplay is a user-centred model, which helps you shift the focus of automated acceptance tests from low-level interactions with the system to thinking about who the users of your system are, what is that they want to achieve by their interaction with your system and how exactly they're going to do it.
Mission helps you modularise your code and create personas which describe business or functional interactions of software users.
Aiming at full answer - a good collection of other patterns in the xUnit world is the xunitpatterns. However, there is not a single pattern solution for your test framework you are building. One should follow and use other design principles and concepts as well. For example, your domain logic (business specific) should be layered in a DSL, having no knowledge of underlying drivers or higher level BDD specifications.
I am new to object oriented programming and learning to design classes.
I am wondering how can i design a class which holds list of itself.
For example, I have a class named Game will following definition:
Game
title
description
screenshot
flash (holds flash game object)
I want to display list of games on a page. What approach is good for it?
Either create another class GameList and create array of Games to be listed or
create a function Game.ListAll to display game list?
I feel former is better approach to do so. I need your guide please.
Also i dont know what to actually study to clear my concepts in designing class and their relationships etc.
Can you please suggest me a book CBT which is easy to understand ?
Thank you very much.
-Navi
I don't know what languague your are using but I can recommend "Agile Priciples, Pattens and Practices" from Robert C. Martin (there is a C# version too). There is a lot about OO design in there too, together with all the important patterns and a nice intro to TDD and Agile - and it's fun to read.
To your question: yes go for your first idea or use a inbuild collection like List<Game> (should be the same no matter if you are using C# or Jave)
I think it would be a bad design to have a (static) method listAll() within Game: Games shouldn't know about other games, you would need the constructors or factory methods to take care of the list, and you couldn't handle separate lists.
So use a list outside of Game. If you do not need special behavior of the GameList, a field List where you treat the list will do. If you have special behavior, your design with GameList is the right choice.
For good OO design, I would read up in the following order:
the relevant articles from the object mentors article list to get an overview. You can find links to the most relevant for you at principles of ood.
a book about design patterns, my favorite still being the classical Design Patterns from the GoF
read Agile Software Development, Principles, Patterns, and Practices from Uncle Bob
I've become pretty enamored of the Seaside web framework lately. I'd like to start digging into the source to figure out how it works. Unfortunately, there are a lot of classes and I don't know where to start! Does anyone know what classes I should try to understand first? I assume that there's a routing class somewhere that I should start with...
Stephan gives good suggestions. Basically, if you understand the Seaside-Core package in Seaside 3.x, you understand how everything fits together:
The Canvas stuff is all a specific implementation of WARenderer from the Seaside-Core-Rendering category
The Session/Application stuff is all a specific implementation of WARequestHandler from the Seaside-Core-RequestHandling category
The Component/Task stuff is all an implementation of WAPainter from the Seaside-Core-Presenters category
There are really two ways of approaching studying the framework. Either start with one of the specific things you are interested in (say WAComponent) and work your way up the superclasses. Then repeat with each of the other classes Stephan mentions.
I'd suggest the other way: starting with the three sets of abstract classes I mentioned in Session-Core. Looking at them together (combined with the HTTP and Document classes) will give you an idea of the generic concepts and how they plug together to form the framework. You can look at each of the specific implementations as needed to relate the generic concepts to the actual implementation.
Subclasses of WAServerAdaptor form the starting point of request handling in Seaside, where a request from a specific web framework is converted into a Seaside request and dispatched to an appropriate handler. Callbacks are also pretty important and are in Seaside-Core-Callbacks.
If you understand everything in Seaside-Core, you basically understand how the framework works at a high level. Once you have a broad understanding of the basic core concepts, you can then proceed to get a deep understanding of each area that interests you by examining the concrete implementations in more detail. But keep in mind that everything in Seaside-Core is intended to be subclasses and plugged together to extend the framework.
I assume you have read the Seaside-Book?:
http://book.seaside.st/book
If you want to go deeper just look at the source, starting with the classes WAComponent and WARenderCanvas+WAHtmlCanvas. The routing class is WAAdmin in the sense as "this is the place where different Seaside-apps are registered".
There are several parts that are interesting. Start from WARenderCanvas to understand how the html generating dsl is build. WAComponent is the starting point for the composite page structure with call: and answer:. WAApplication represents a Seaside application, WASession a session, WAServerAdapter connects the Seaside framework to a http server and WARequestHandler handles http requests. The Grease package handles differences between Smalltalk dialects.
You are using the different browsers (class and hierarchy), class commments and senders and implementors, aren't you?
In Martin Fowler's Patterns for Enterprise Application Architectures book (page 229 in German, Lazy Load) he gives an example with this code:
public List getProducts() {
if (products == null) products = Product.findForSupplier(getID());
return products;
}
like you can see, the finder method seems to be part of the domain class Product. This confuses me a little bit, since I thought everything related to retrieving objects from somewhere (often a database, but business logic shouldn't care) should be part of the Data Mapper (PersonDataMapper) class. Probably I just missed something?
The example you gave is the easy method for Lazy Loading. Person is unlikely using a DataMapper. As Fowler states in the english book (201):
Using lazy initialization is simple,
but it does tend to force a dependency
between the object and the database.
For that reason it works best for
ActiveRecord, Table Data Gateway and Row Data Gateway. If you are
using Data Mapper, you'll need an
additional layer of indirection, which
you can obtain by using a virtual
proxy [GOF].
As for everything [...] should be in the DataMapper, well.. yes, but also no.
What you should keep in mind when working with design patterns is when to use them and when not. DataMapper is not the Holy Grail. It's not the only way to do it. When your app is just a small and simple CRUD app living on the web, then the added complexity of a Data Mapper and/or using a Domain Model is likely not worth the effort.
In addition, design patterns are generic good practise approaches to common software problems. While you may be able to apply them to your concrete problems as they are given in a book, there is no reason to follow them religiously. If something in a pattern would overly complicate your problem solving, then keep it simple. Derive. Adjust. Solve the problem.