How do I avoid magic strings (PHP MVC Frameworks) [closed] - php

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I want to use a MVC-framework together with PHP to make a nice separation between code and presentation. I've currently started to look at CakePHP. It looks nice, but whats about all those magic strings?
Take a look at the code below (taken from the CakePHP cookbook):
class User extends AppModel {
var $name = 'User';
var $hasOne = 'Profile';
var $hasMany = array(
'Recipe' => array(
'className' => 'Recipe',
'conditions' => array('Recipe.approved' => '1'),
'order' => 'Recipe.created DESC'
)
);
}
It bothers me with those magic strings. Strings in code ought only to be text to be outputted!
One spelling mistake in 'Recipe.created DESC" and it won't work as expected. There's no intellisense/code completion to help here!
Also, what if I want to remane 'Recipe' to something else? I have to search manually through all the code and find out if it's regular text or one of the magic strings.
Are other PHP MVC-frameworks better? (read: less or no magic strings)
Any links on how to avoid magic strings (at least as much as possible)...?

Cake follows the 'Convention over Configuration' methodology. It's a framework that can be used to rapidly prototype and deploy (mostly) CRUD based applications. It's got a lot of 'magic' happening behind the scenes which don't always make it a good choice if you don't know what's going on under the hood.
As to your specific example, it isn't too bad. Recipe actually refers to a Recipe model that the User model is related to. Cake has an inbuilt ORM that uses some model variables to set your model relations properly. This would be the case in any ORM framework, I'd say. Unless you changed the class name, you wouldn't need to change all the references, this would be true in any PHP code.
As to other framework recommendations. I'd suggest that you work with your own PHP MVC stack before you begin to work with frameworks. If you have a fair understanding of PHP, you could look at the CodeIgniter or Kohona framework. These are less rigid than Cake. You could also have a look at the Zend Framework. There are many other frameworks out there that have different features (more or less with differing variations of control offered), all you need to do is look around.

What you are searching is the good ORM. Try using one of these:
http://www.doctrine-project.org/
http://framework.zend.com/
http://www.symfony-project.org/
http://kohanaframework.org/
More about ORM:
http://en.wikipedia.org/wiki/Object-relational_mapping

I see what you did there
Also, what if I want to remane 'Recipe'...
No matter which ORM library you choose there will always be magic strings. There just isn't enough information to automatically map your class to a database table (except in the simplest cases). The magic strings are really meta-data that the ORM needs to create the mapping.
You can try to avoid magic strings by defining constants or creating public static fields, but ultimately you will have only consolidated them to, at best, a single file.
When working with an ORM you will have to provide meta-data no matter what. With that in mind, you should choose the ORM that feels most comfortable to you.

Related

PHP: should I be writing all my code in classes? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I've been coding with PHP for a while now, but I've been mainly coding with Functions and raw PHP.
I've started to think that I should be writing my code a whole lot neater and more efficiently. I still can't quite get my head around classes. Should I be writing ALL my code in classes?
For example, one of my scripts is a 'permissions manager' - which allows an admin to edit the permissions of various user groups on the site.
Traditionally, I'd have written this as just a script with functions and whatnot. But would it better to write this as a class? If so, what would this class contain? Would I have a separate permissions class for use around the site, and another for the admin-editing area?
Also the site has an API. Should this all be written as one class?
Also, should I be using public (shared) functions at all?
Thanks!
In my opinion everything depends on how large is your project. I've worked using Magento for a while and it's so big that it must be grouped in classes and packets. It's easier to read code and analyse the structure of project if it's split in classes. Also when you need to modify your project after a month or year then good structure helps to re-learn it.
It is useful to write stuff in Classes when a particular set of functions and variables belonging and/or oriented to the same entity or propose is to be used in different environments. It gives a sense of organization, delegation of tasks and avoids repetition of code.
But in situations where the above is false, it is completely disposable. Theres no point in writing a class to something that will run only in one specific place.
Also, if you only want to have a set of information organized in an object-like style like in $user->name, $user->age etc. you can simply do this:
$user = (object)array(
'name' => 'John',
'age' => 20
);
Yes, in my point of view it would be better to make your code in OOP to be more neat, understandable, readable and also for maintenance it will be more easy,
Please take a look here in this stack :
https://stackoverflow.com/questions/4409824/what-are-the-advantages-of-object-oriented-php
You should approach that question from a different angle. Don't just use OOP because you think you have to.
Ask yourself:
Are there parts of my application that I could reuse in other parts of my application? Then these could be taken out of your script and be put in a function or class.
Is there a scenario where you would like to exchange parts of your code to change the behaviour without having to rewrite major parts of your application? Then classes and interfaces are for you.
Another good argument for using OOP principles is the increased testability of your code. Using interfaces allows you to exchange the actual object for a mock or stub at test time.

Model and backend interface generators for Zend Framework [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
By doing some research, one of the disadvantages often reported about Zend Framework is the amount of work required to get off the ground. For me this could be addressed if ZF had strong model and backend interface generators like Symfony does. I have been looking for those and here is what I found:
Model generators
http://code.google.com/p/zend-db-model-generator/: looks like official one, based on user feedback, the documentation seems to be awful though.
http://code.google.com/p/zend-model-generator/: seems quite advanced. updated 3 months ago.
https://github.com/inxilpro/Galahad-FE/: not updated in 2 years, looks dead.
https://github.com/codeinchaos/zend-model-generator/blob/master/generate.php: single php file, could be interesting to use as basis and extend as needed.
Backend interfaces
As usual one can use database administration tools
http://www.phpmyadmin.net: quite complete with plenty of new features since 3.5. Hard to extend.
http://www.adminer.org/: single-file backend interface. Quite complete. The use of plugins seems to make extending functionality easy.
Backend interface generators
http://zfdatagrid.com/grid/default/site/crud which comes from what looks like a very active ZF related project: http://code.google.com/p/zfdatagrid/.
http://www.koala-framework.org/: I've recently come across this framework which allows you to create "desktop-like" applications around Zend, which one could use to create a backend interface.
Setting up the interface seems to be quite easy, for instance here is how you would display a form to edit contacts on the same page as you would edit members:
<?php
class MemberContacts extends Kwf_Model_Db
{
protected $_table = 'member_contacts';
protected $_referenceMap = array(
'Member' => array(
'column' => 'member_id',
'refModelClass' => 'Members',
)
);
}
?>
A demo of Koala frameworks is available. To be honest it looks quite impressive.
Q: Which model generators and backend interface (generators) do you use for Zend and why?
I do not use any kind of generator, prepared backoffice or so called scaffolding.
Why I don't use them in a general way ?
These tools introduce a strong dependencies on the way the generated UI is structured, you do not have anymore the power to design it the exact way you want.
They are quite hard to reuse unless you know them very well, they introduce a lot of magic, for example when I create a backoffice using Django I've to set five parameters and I've a backoffice running. Understanding how it works do really need a lot of knowledge on the inner mechanisms of the tool, so updating it can be a real pain.
To my mind there's a strong difference between providing almost complete backoffice application like Symfony, Rails and Django do, and what Zend Framework do: constraining to general framework and libraries.
There is a deliberate choice between something working out of the box and something flexible. I think they tend to aim different needs.
I tend to prefer the Zend Framework approach since I'm not satisfied (nor experienced I've to admit it) with what others offer as an "almost done" UI.
Why I won't ever use them in Zend Framework ?
If Zend Framework doesn't embend such tools, I won't plug what others have tried to build upon it since nothing can guaranty that there won't be any regression on it (and upgrading can be a really good thing since Zend always integrate more and more external services). The power of Zend Framework is its flexibility, by overlapping tools over it, you're going against the philosophy of the product.
It might meet your expectation on really small project, but for bigger one I do really suggest you to build your UI according to your own needs, the backoffice will only take only you one or two weeks more.

Simple object-oriented exercises for grasping the basics [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I'm teaching a few friends some basic object-oriented concepts in PHP and i wanted to give them some real-world examples, but simple, so they can grasp the syntax and the basics of OO. I already gave them the following exercise: create a small class that abstracts HTML form creation. You can create objects for each form field, each type of field has a class. I also have a form class which receives form field objects.
Do you guys have any other ideas of examples or exercises? Thanks!
My blog post about Objects in PHP might be useful:
http://agiletoolkit.org/blog/how-to-use-object-oriented-programming-in-php/
It gives example how to macerate "geometry" classes, triangle, vector, square etc.
When I was learning OOP, I was reading a book with similar examples in C++, but I forgot the name.
A simple exercise I've always enjoyed for getting into an object-oriented way of thinking is to take some simple real-world concept and model it into objects. These concepts can be anything:
A coffee maker
A chicken
A bicycle
etc.
It's very language-agnostic, platform-agnostic, etc. The idea is to abstract out all of the implementation details (things like PHP and HTML) and focus on object-oriented thinking. How does a model for such an object look? What are its attributes? What are its constraints? How does it behave? How does it interact with other objects?
You can effectively design your abstract types by their external observable characteristics and behaviors, their interactions, etc. and then implement those abstractions in PHP or any other language of choice. But the point is to separate out the object-oriented thinking from the specific implementation.
Some things that are usable/practical:
Almost everybody seems to start with a database abstraction library. Very simple to do
Abstraction for different caching libraries (memcache, apc, file cache)
Perhaps a simple router
Try a table generation class, where they receive an array and, depending on it's contents, a table is displayed.
It depends on how much they know already, if they have experience of programming in C++/C and are starting OO, then examples from Databases, forms, vector etc would work, if they have relatively little experience, then you have to start with abstract or real life examples, examples quoted in another reply
A coffee maker
A chicken
A bicycle
etc.
will work great (despite you have mentioned you do not like such examples) in understanding the concept of Object Oriented and the theory behind it. They have to see how everything works together to form a machine, how each component (class) works and interacts (public methods and interfaces) while hiding its own functionality, and providing a set of services to other components (classes).
A very popular examples teachers give is of a radio, where the user doesn't know what is inside the radio and how it works, the user only knows what it does, and the radio makes its features available to the user for use through the buttons on the panel.
These basic examples work well for beginners, and then immediately there should be a programming assignment related to it. Once they understand the basics, programming and application examples instead of abstract examples should be used in my opinion.

How to implement service layer in Zend Framework? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I'm looking for some good resources to learn how to implement internal service layer in Zend Framework. This is interesting post Bookie Link, but with no concrete code samples.
Where to put service classes (/application/modules/modulename/services/?);
How to autoload them (custom autoloader?)
Most common services (user, authentication, cart, cache, feed?)
Sample implementations (any github repos?)
Good practices?
I think the answer to this question depends on your needs, your time constraints and your overall approach to/style of software development.
I have recently (A) made the decision to use Zend Framework on a small but complex web application that has a very tight deadline and (B) have spent a LOT of time investigating ORM solutions and different ZF application structures in general. The conclusion I have come to is that there isn't a one-size-fits-all solution and that you should feel free to get creative and build an application structure that you are happy with.
If you have tight time constraints and the application isn't too large, then you could just create classes with names like Application_Model_BlahService and store them in the application/models directory and they will get picked up by default by the autoloader (assuming the autoloader has been bootstrapped correctly).
But if your application is larger or if, for some other reason, you want to split classes out into more directories, you could create your own sub-directories under the application directory and use something like the code below (which would exist in your application/Bootstrap.php) to add those classes to the autoloader:
protected function _initResourceLoader()
{
$this->_resourceLoader->addResourceType( 'service', 'services', 'Service' );
$this->_resourceLoader->addResourceType( 'serviceplugin', 'services/plugins', 'Service_Plugin' );
}
You can then create classes like Application_Service_Invoice, which would reside in application/services/Invoice.php and Application_Service_Plugin_TaxPlugin, which would reside in application/services/plugins/TaxPlugin.php. (Note: the code above assumes you are using Zend_Application).
You could, in theory, take this as far as you like and separate model classes from service classes from data access classes, etc etc etc. But again, it depends on the style of development that you prefer, the size of the team and, to some degree, what requirements your persistence layer imposes on you.
One last quick thing: have a look in Zend_Application_Module_Autoloader for a list of resources that are added to the autoloader by default. (Should I have mentioned that I'm referring to ZF 1.8+ in this answer?)
You don't need hacking to get service layer work. Default autoloader has a resource namespace Service_ with services folder inside application. So, it will load service layer from application\services, classes should follow Service_* naming pattern.
Basically, you could probably put those anywhere you like ; somewhere close to the model will most likely make sense, though.
As an example, you might want to take a look to :
ZFPlanet : an example of a planet developped with ZF
Not sure it's finished, but there are several classes, controllers, models, config files, ...
Which means that going through the code can help (it has, for me, for some things)
And, especially, its application/modules/zfplanet/models/Service directory
Which contains two classes.
(Well, I hope that's the sort of thing you meant by Service, actually)

How to implement MVC from scratch in PHP? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I would like to implement MVC from scratch in PHP because I want full control of my own code
and no extra bagage from existing frameworks. Anyone who has any advice?
Yes, I've seen Lerdorfs article and it seems that it ain't so much code after all. Actually I would more like to have a controller-view solution for structuring my application. I'll stick to my own homemade PDO data-access classes.
Your question somewhat smells like Not-Invented-Here-Syndrome. In this case, my advice would be to live with the extra baggage of existing frameworks when you can be sure they are thoroughly tested and supported. Don't reinvent the wheel.
On the other hand, the above argumentation would prevent new frameworks to be written. And writing one from scratch is a good coding exercise to learn and understand the MVC pattern.
So if you are really determined to do it, my suggestion is to learn what each part of MVC is, does and how they interact. You will inevitably come across the FrontController pattern as well, so you will want to learn about this one too.
Note that you are not the only person wanting to do this:
http://www.google.de/search?q=front+controller+php
http://www.google.de/search?q=build+your+own+mvc+php
And there is also this interesting article by Rasmus Lerdorf
http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html
A simple exemple implementation of MVC (just to understand the principle)
MODEL: lib/Thing.class.php
class Thing
{
//class code ( CRUD, the application logic ...)
}
VIEW: theme/page_thing.php
<?php require("header.php");?>
//HTML CODE with some echo to show variables and loops to read arrays
<?php require("footer.php");?>
CONTROLLER: application/thing.php
require_once("lib/Thing.class.php");
/*
Some controls between the Model and the View ( if/else ...)
*/
include("theme/page_thing.php");
I, too, wrote an homegrown MVC framework in PHP. Its pretty simple, especially when you remove any "ActiveRecord" functionality from your frame work. Some things that I considered:
How are you going to map URLs to controllers?
Instead of doing things by convention (/foo maps to FooController), I did everything via configuration. That is, I have a master routes.php file wherein I list every possible URL that my application will accept. So its filled with things like:
Router::add( '/foo/:Param1/:Param2',
array( 'Controller' => 'MyController',
'Action' => 'my_method',
'Method' => 'GET',
'Parameters' => array( 'Param1' => '\d+',
'Param2' => '\S+' ) );
In this case we match urls like /foo/123/abc. When the URL is matched, it is dispatched as MyController::my_method( array( 'Param1' => '123', 'Param2' => 'abc' ) );.
How are you going to generate views?
There are lots of templating systems out there. But really, PHP is already a perfect templating system. In my framework, I just created a function template() in the top-level Controller class. And it all boils down to performing an include $Template. Again, in my framework, there is no convention. Each controller is responsible for instantiating the appropriate template, and for understanding if the request is expecting HTML, XML, or JSON as a response.
Can you use an existing framework?
A lot of my code was inspired by Cake, the well-known PHP MVC framework. I'd definitely take a peek at it before you proceed to far. If you're going to roll your own, at least start by understanding how all of the popular ones work. In the end, the peculiar requirements of my application made me go down the road of build my own, but there was a lot to be learned from all the frameworks already out there. Take a long look around, and you may find something that works for you. At the very least, you may figure out exactly what you need out of your framework.
I personally use my own framework consisting of :
1.Mysql Interface
2.Template System (yes home brewed not smarty)
3.Config Class (mysql details,debug, and anything else that the script might need)
4.Simple Form Creating class.
5.a Request Class (all useful details from $_SERVER in a more readable format ex: $this->Request->ip, $this->Request->url,$this->Request->time)
6. Anti-hacking (Ip blacklist, keywords from public sec. scanners etc.)
And I just call it framework :)
if you're just going to "recyle" the wheel, you can take a look at the source code of "popular" frameworks. if you want to "reinvent" the wheel, i suggest you look elsewhere. examine domain-specific languages (DSL).

Categories