Best Practice: Symfony2 DataGrid - php

I was wondering if someone can help be to point me to an example for a "Best Practice" example for a sortable, searchable datagrid in Symfony2 with the doctrine ORM.
I always see Tutorials with the implementation of some data, generating Entity and so forth, but some/all lack the code how to enable Pagination, how can the user search in multiple fields from the frontend and how to handle the ordering after a field the user chooses to.
Before some folks now think I'm stupid, of course i can make a GET Variable and just make an IF clause to ask for it but i would really appreciate a best Practice example so i know how i am supposed to handle it.
Right now I'm thinking about an open source project for a Organisation system, so i will have many Tables i have to join and many datagrids to display. I would really love to get it in a right way so i don't have to write it all over again when the community is laughing at my code...
Thank you for reading and your help.

I use apy data grid bundle https://github.com/Abhoryo/APYDataGridBundle
It works very well and it's very simple to use

For your goal, you can take a look a SonataAdminBundle in which you can describe by yaml, for instance, you entities relations, search operands, and you'll have a full application to do CRUD and search without much trouble. I setup my basic crud/search operations on the 20 basic entities in a day or two.
I honestly don't know how sonata is organized and if the datagrid is "extractable" or if you could use it as a service, but I believe is a good starting point.

Related

Easiest Way to Fire Queries In magento (Entity attribute value model)?

I am new to Magento and its EAV Model. I am very much confused about its database structure. It's really hard to find data inside tables even when I browse through phpmyadmin. Then it becomes more complicated and time consuming when I try to write queries to fetch data from its tables.
Is there any simple way to understand and deal with this type of database? And is there any simple way to fire queries in it. I tried hard searching internet to get some good tutorials to understand this kind of database but couldn't find. Can anyone suggest any good book or online material to understand Magento database and EAV Model? Thanks
I would suggest taking a look at http://www.alanstorm.com/category/magento and reading through the Model sections. One of the best tutorial/learning sites I've found out there for Magento.

CakePHP for big projects

We are evaluating some PHP Frameworks for a productive website. CakePHP looks pretty interesting but we have no clue if it fits our needs.
Basically when you check the documentation and the tutorials for CakePHP it looks really promising. Nevertheless there were always some things that bugged me with frameworks so far, maybe someone who already used CakePHP in a productive project could answer this questions for me?
Writing/Reading data for single records looks pretty neat in CakePHP. What happens if you want to read data from multiple tables with complex conditions, group by, where clauses? How does CakePHP handle it?
Scaffolding looks pretty nice for basic administration interfaces. How easy is it to customize this stuff. Let's say I have a foreign key on one of my tables. When I create a scaffolding page, does CakePHP automatically create a dropdown list for me with all the possible items? What if I want to filter the possible items? Let's say I want to combine two fields into one field in the view part, but when I edit it, I should be able to edit both of those fields individually. Does this work?
Do you think you were faster in development with CakePHP than with let's say plain PHP?
I've used CakePHP, Zend Framework and I've also written applications "from the ground up" with nothing more than homegrown classes and such. To that I'd like to mention that I use CakePHP regularly so, take that as you will.
(Writing/reading data, complex conditions) You can certainly do everything you mentioned. Others are correct in that it attempts to abstract away SQL operations for you. I've yet to have a query that I couldn't translate into Cake's "parlance"; complex geospatial queries, joins, etc.
(Scaffolding, complex conditions) The scaffolding is really only meant to serve as a "jump start" of sorts to help make sure your model associations and such are setup correctly and should not be used as a permanent solution. To that end, yes it will do a fairly good job at introspecting your relationships and providing relevant markup.
(Faster development) Of course. There is a large community with a vast number of plugins or examples out there to help get you started. Regardless of what you pick, choosing a framework will almost certainly make you "faster" if only for handling the minutiae that comes with setting up an application.
It really depends on your definition of "large". Are you referring to big datasets? A very complex domain model? Or just lots and lots of different controllers/actions?
Writing/Reading data.
Anything you can do with plain SQL you can do in CakePHP. It may not always be very nice to do, but at it's worst it's no worse than straight SQL.
But you really shouldn't be thinking about queries. You should be thinking about your domain model. CakePHP implements the active record pattern. It works very well if your domain model maps nicely to an active record pattern. But if it does not, then I would not recommend CakePHP. If your domain model doesn't map to Active Record then you will spend a lot of time fighting the Cake way of doing things. And that's no fun. You would be much better off with a framework that implements a Data Mapper pattern (e.g. Zend).
Scaffolding
Scaffolding is temporary. It does handle foreign keys (if you define them in the model as well as in the database) but that's it. You can't modify the scaffolding. But, you can bake them!
When you bake a controller or view then you're basically writing the scaffold to a file as a jump-off point for your own implementation. After baking, you can do anything that you want. The downside of baking is that it doesn't update anymore when the models or database changes. So, if you bake a controller and views and you add fields to your model, then you need to add those fields manually to your controller and view code.
speed of development
In my case, I'm a lot faster developing a website in CakePHP then in plain code. But only if Active Record suits the application! See my first point. Even then, Cake is probably still faster, but I would be faster still with a better suiting framework.
Some other thoughts
large datasets
If you have very large datasets and big query results then Cake can be a problem. A find() operation wants to return an associative array, so all the rows are read, parsed and converted to arrays. If your result set is too large you will run out of memory. CakePHP does not implement ResultSet objects like many other Active Record implementations and that is a definite downside. You end up manually paging through your own data with subqueries. Yuck. Wich brings me to my next point:
arrays
Learn to love them because CakePHP does. Everything is an array and often they are large, complex and deep. It gets really annoying after a while. You can't add functions to arrays so your code is more messy than if CakePHP would have used nested object instances. The functions you can add to those objects can help keep your code clean.
oddities and inconsistencies
CakePHP has some real nasty stinkers hidden deep within. If Active Record suits your application then you will probably never run into them, but if you try to mold CakePHP into something more complex, then you will have to fight these. Some examples:
HABTM through a custom model uses the definition from the other side of the relationship that you're working on.
Some really odd places where your before/after triggers aren't called (e.g. not from an updateAll)
odd Model->field() behavior. It always queries from the database. So, be careful about updating model data without immediately saving it to the database. Some CakePHP functions fetch data from Model->$_data and some use Model->field(). The result may be entirely different resulting in some very hard to track down bugs.
In short
I would highly recommend CakePHP even for "large" sites, as long as your domain model fits nicely on top of Active Record. If not, pick a different framework.
Since you are asking for opinions, then I have to say that I advise AGAINST CakePHP.
My biggest gripe with it, is that it's still using PHP4 (written in and code generated). So, why go backwards? It is compatible for PHP5, but the framework itself revolves around PHP4.
I would recommend taking a look at Symfony or Zend. Symfony being the best if you want more structure in place - it forces you to adhere to the MVC structure that it has established.
The alternative is Zend, but it's more of a 'do-it-yourself' framework, or rather more of a set of libraries. You need to put it all together yourself, and it doesn't have any strict structure like Symfony.
There are obviously other frameworks, but I recommend the fore-said. Another one that you may want to look at is Codeigniter.
CakePHP tries to abstract away the database, so you write very little SQL (however, you write a lot of SQL snippets).
The basic process is to define your models, then define the relationship between models (hasOne, belongsTo, hasMany, hasAndBelongsToMany). You can put any conditions or default ordering on these associations you like. Then, whenever you fetch a row from the database, any associated rows are automatically fetched with it. It's very easy and powerful.
Everything comes with a bunch of configuration options, giving further flexibility. For example, when fetching data there is a recursion option which takes an integer. This value is how many associations deep Cake should fetch data. So if you wanted to fetch a user with all their associated data, and all the joined data to THAT, it's trivial.
Pretty much anything can be overridden on defined on the fly, and you can always fall back to writing your own SQL, so there's nothing Cake prevents you from doing...
I've not found much use for scaffolding. The answer to your question is yes, it'll auto populate joined dropdowns, etc. But I've never used it as a basis to build an interface. I tend to use a database tool to populate data early on rather than scaffolding.
I've built and also maintain several web-apps on CakePHP, and it is without question faster than 'rolling your own'. But I think that's true of any decent framework!
Unfortunately one of the weaker points is the documentation. Often you need to Google for answers as the official documentation is a bit hit-and-miss at times.
Just go with Yii framework, it's the best in this category.
(Note: This is a subjective question. You are asking for opinions. So I hope you don't mind if I give mine.)
(Edit: Ops. I mixed Cake with CI)
I used Code Igniter a while back. It did everything it should and was fairly easy to understand. However, for big projects, it lacked features. Many CI proponents say that this is it's strength as it keeps it fast and can make little RAM. This is true.
However, after developing one application with it, I found myself looking elsewhere so I would not have to write code that must have been written before. I looked at CakePHP and found it too restrictive and automagical. In particular, I needed some kind of ACL functionality. This lead me to Zend Framework. I learned that it is loosely coupled. I can include only the files I need. I can also make use of Zend_Application for large projects. It's object oriented design is a must when developing and maintaining large projects.
Yes, CI and CakePHP helped me to develop faster than with plain PHP. However, there are much more powerful frameworks. I hear and see good things about Symphony. There are quite a few more. I'm sure others will point them out.

Handling complex data collection with a CMS

I do web work for a group at the university I attend. We’re having a design company redo our site and will be coding the site ourselves. We’d like to build the new site on top of a CMS so that people can easily add content. So far I’ve been looking into using Drupal. The problem I’m running into while thinking through how well Drupal will work for us is in regards to data collection. We’re overhauling our database to keep data centralized. For example, rather than create a table for every form with fields for First Name and Last Name (common fields for a lot of the forms we do) and all other fields, we’re pulling the common fields out to tables like a user table. This will help us track people’s involvement with our group much better and make our data far more useful. Is there any easy way to do this with Drupal modules? I’ve looked into CCK a bit but it doesn’t look like it’s useful for more than simple data that doesn’t have “complex” relationships between tables.
What are your recommendations? Are there some good modules I could use; do you recommend a different CMS (NOTE: needs to be php) that would better suite my needs?
I have the same exact question as you -- so far the best CMS I've come across for data collection from forms is Concrete5 (http://concrete5.org). Any time you use their "form" block, the submissions are sent to the "Reports" section on the back end of the dashboard. I don't love their organization method, but it's the best I've seen so far, and it also lets you dump to a file.
I think you want Drupal with Views and Organic Groups.
What kind of forms do you have?
You shouldn't use Drupal if you care about database structure. CCK is the method of defining content types, used on 60% of all Drupal sites and the basis of fields in Drupal 7 core.
That said, you may want to question a few of your assumptions. First, there are a lot of modules that add new field types to CCK, e.g. FileField, so it may not be as simple as you think. Second, do you really need to worry about how the database is organized, or is that just a means to some other end, e.g. reporting. If it's reporting you're after, you can generally handle that with Views, the only module used more than CCK.
If you really do need to worry about the database structure and really do need more complex relations than CCK can handle, I'd suggest you're not looking for a CMS so much as a framework. Those kinds of details are generally handled automatically in a CMS.

PHP Commercial Project Function define

Currently I am working with a commercial project with PHP. I think this question not really apply to PHP for all programming language, just want to discuss how your guys solve it.
I work in MVC framework (CodeIgniter).
all the database transaction code in model class.
Previously, I seperate different search criteria with different function name.
Just an example
function get_student_detail_by_ID($id){}
function get_student_detail_by_name($name){}
as you can see the function actually can merge to one, just add a parameter for it. But something you are rushing with project, you won't look back previously got what similar function just make some changes can meet the goal. In this case, we found that there is a lot function there and hard to maintenance.
Recently, we try to group the entity to one ultimate search
something like this
function get_ResList($is_row_count=FALSE, $record_start=0, $arr_search_criteria='', $paging_limit=20, $orderby='name', $sortdir='ASC')
we try to make this function to fit all the searching criteria. However, our system getting bigger and bigger, the search criteria not more 1-2 tables. It require join with other table with different purpose.
What we had done is using IF ELSE,
if(bla bla bla)
{
$sql_join = JOIN_SOME_TABLE;
$sql_where = CONDITION;
}
at the end, we found that very hard to maintance the function. it is very hard to debug as well.
I would like to ask your opinion, what is the commercial solution they solve this kind of issue, how to define a function and how to revise it. I think this is link project management skill. Hope you willing to share with us.
Thanks.
If you're using codeigniter, just use:
http://www.overzealous.com/dmz/
I don't know what I even used to do without it.
Congratulations, you have invented an ORM :)
There are plenty of commercial ORM solutions but, in my opinion, all they no better than yours. And I'd go for good ol' SQL.
After I did some research on ORM vs Active Record. For my situation I didn't find a lot of help by switching to ORM will help me better.
I found out that ORM is not do very in READ data. But good in Create, Update, and Delete.
My current solution is every model recompile the my own OR_WHERE() / AND_WHERE(), before pass to the $this->db->query(). It is more easy to maintain and customize.

How do I write object classes effectively when dealing with table joins?

I should start by saying I'm not now, nor do I have any delusions I'll ever be a professional programmer so most of my skills have been learned from experience very much as a hobby.
I learned PHP as it seemed a good simple introduction in certain areas and it allowed me to design simple web applications.
When I learned about objects, classes etc the tutor's basic examnples covered the idea that as a rule of thumb each database table should have its own class. While that worked well for the photo gallery project we wrote, as it had very simple mysql queries, it's not working so well now my projects are getting more complex. If I require data from two separate tables which require a table join I've instead been ignoring the class altogether and handling it on a case by case basis, OR, even worse been combining some of the data into the class and the rest as a separate entity and doing two queries, which to me seems inefficient.
As an example, when viewing content on a forum I wrote, if you view a thread, I retrieve data from the threads table, the posts table and the user table. The queries from the user and posts table are retrieved via a join and not instantiated as an object, whereas the thread data is called using my Threads class.
So how do I get from my current state of affairs to something a little less 'stupid', for want of a better word. Right now I have a DB class that deals with connection and escaping values etc, a parent db query class that deals with the common queries and methods, and all of the other classes (Thread, Upload, Session, Photo and ones thats aren't used Post, User etc ) are children of that.
Do I make a big posts class that has the relevant extra attributes that I retrieve from the users (and potentially threads) table?
Do I have separate classes that populate each of their relevant attributes with a single query? If so how do I do that?
Because of the way my classes are written, based on what I was taught, my db update row method, or insert method both just take the attributes as an array and update all of that, if I have extra attributes from other db tables in each class then how do I rewrite those methods as obbiously updating automatically like that would result in errors?
In short I think my understanding is limited right now and I'd like some pointers when it comes to the fundamentals of how to write more complex classes.
Edit:
Thanks for the answers so far they've given me lots of pointers and thoughts and a lot of reading material. What I would like though is maybe an idea of how different people have decided to handle a simple table join with any amount of classes? Did you add attributes to the classes? Query from outside the class then pass the results into each class? Something else?
Entire books have been written about how to design a set of classes to fit a database schema.
Long story short: there is no one-size-fits-all way to do it, you have to make a lot of design decisions about the trade offs you want to make on an application-by-application basis.
You can find a library or framework to help, keywords: ActiveRecord, ORM (Object Relational Mapper)
P.S. You have no idea the potential for soul-killing analysis paralysis and over designing you can get into. Do the simplest thing that can possibly work for your app.
Code sample for my (below) comment:
$post = new PublishedPost($data);
$edit = $post->setTitle($newTitle);
$edit->save();
This is too broad to be answered without going into epic length.
Basically, there is four prominent Data Source Architectural Patterns from Patterns of Enterprise Architecture: Table Data Gateway, Row Data Gateway, Active Record and Data Mapper. These can be found implemented in the common php frameworks in some variation. These are easy to grasp and implement.
Where it gets difficult is when you start to tackle the impedance mismatch between the database and the business objects in your application. To do so, there are a number of Object-Relational Behavioral, Structural and Metadata Mapping Patterns, like Identity Maps, Lazy Loading, Query Objects, Repositories, etc. Explaining these is beyond scope. They cover almost 200 pages in PoEAA.
What you can look at is Doctrine or Propel - the two most well known PHP ORM - that implement most of these patterns and which you could use in your application to replace your current database access handling.
Many of your worries can be answered by inspecting the existing solutions found in well-tested frameworks such as CakePHP, symfony and Zend Framework. Examining their approaches and peeking under the hood should shed light on your questions. Who knows? You may even decide to write future projects using them!
They've spent years putting their heads together to tackle these problems. Take advantage!
Checkout Doctrine:
Here is an example of a forum application using Doctrine.
http://www.doctrine-project.org/documentation/manual/1_2/en/real-world-examples#forum-application

Categories