Skip navigation

Following up with my last 2 posts about Widgets and Controllers, the past couple of days I got my hands dirty with Models. Models are created inside the Models directory in a module. A model represents an item, or an object, which is fetched from the database. To describe how things work, I think the simplest way is to use an example.

If you find anything that is inconsistent or does not work, please let me know in a comment or so.

Assume we want to allow the user to categorize his friends (like facebook friends lists). So we’re going to create a table in the database to store this.

From my understanding, the convention of SE (probably zend too) in table names goes like this:

prefix_modulename_tablename

prefix is similar for all tables. It’s actually set somewhere in config files (can’t remember where). modulename is the name of module containing the model for our table. tablename (in plural form) is the actual name of table we’re creating. So, in our example, I’ll assume we’re working inside the “User” module, so we create the table “prefix_user_friendslists“.  We will just give the table a column for primary key  (friendslist_id), creator id (user_id), and category name (list_name).

Note that you must call the primary key column (friendslist_id) as zend automatically infers that from the table name.

Now let’s get started on how to deal with this table from within our application. Inside the Models directory, there is another folder called “DbTable“. DbTable files are most probably the lowest layer files you’ll need to deal with to create models from the database.  A DBTable class is what connects your table to it’s model. So start off by creating a DBTable file (inside DBTable folder) for our table.

Friendslists.php (plural):

class User_Model_DbTable_Friendslists extends Engine_Db_Table

{

protected $_rowClass = ‘User_Model_Friendslist’; Singular

}

$_rowClass chould have class name of our model (that we will create next). This way Social Engine (or zend) would know that results obtained from “User_Friendlists” table, should be assigned to our model. Don’t be confused about singular/plural conventions. Actually if you think about it, DBTable represents the table from database, that’s why it has  plural form like the table name. While a model represent a single object from that table, so it has a singular form in ists class name.

Now in the Models directory create:

Friendslist.php (singular):

class User_Model_Friendslist extends Core_Model_Item_Abstract

{

protected $_owner_type = ‘user’;

}

With $_parent_type and $_owner_type we are getting rid of a manual JOIN operation to get the creator of a category. This way whenever we call $category->getOwner(), its creator”User” object is automatically fetched using the “user_id” column.

Querying the table:

To query our table we first tell the Engine API which table we are going to query against:

$table = Engine_Api::_()->getDbtable(‘friendslists’, ‘user’);

Notice how function paramaters (tablename, modulename)

To select all friendslists a certain user created:

$select = $table->select()  ->where(“user_id = ?”, 1);

$result = $table->fetchAll($select);

foreach($result as $list)

{

echo “{$list->list_name} <br/>” ;

}

A single $category (inside the foreach loop) is an instance of the model we’ve created above. You can use it to access any column by its name.

To create a new category:

Engine_Api::_()->getDbtable(‘friendslists’, ‘user’)

->insert(array(

‘user_id’ => 1,

‘list_name’ => “Shiny new category”

));

Next to come is how to create your own module.

36 Comments

  1. These are really useful tutorials, thanks. You may have noticed that I posted links to your first two on Se4.me and the folks at Webligo are working on producing further tutorials along similar lines. We’re also looking at building a wikipedia for SE4 for those of expanding its functionality through the whole MVC framework. If you haven’t already done so, you’d be very welcome at SE4.me

    • Hey Steve thanks a lot! A wiki would be a great move! I was surprised there were no guides whatsoever for SocialEngine developers. That’s why I decided to start this series of posts. I’ve just joined SE4.me (tgalal), thanks for inviting me.

  2. Thanks for these tutorials, and for joining us at SE4.me – i also think Steve’s idea of a Wiki is a great idea and i’m looking for input from people re which wiki/forum/platform to use for this. Suggestions from yourself and others would be most welcome, since i want to move ahead with the project this week. http://se4.me/forums/topic/view/271

    • Wiki would be much better than a forum as tutorials would be posted AND moderated by the developers themselves. Frankly I’m not familiar with the different wiki software out there so can’t really recommend a specific one. However once this is up, I’d be happy to contribute to it.

  3. You can also use inflected table names, i.e.

    engine4_user_friendlists

    User/Model/DbTable/FriendLists.php

    class User_Model_DbTable_FriendLists

    $table = Engine_Api::_()->getDbtable(‘friendLists’, ‘user’);

    The prefix is set in application/settings/database.php

    • Hey, thanks for the tip! There is also a function that returns the table prefix. I just can’t remember the function name or even where I first found it 😦

    • Do you know how to connect another database other than the default one that is configured in database.php

      how can I add another definition ad use it in my SocialEngine custom controller?

      thank you

      • Actually I’m not sure how to do it, but googling for “Zend multiple databases” returned some useful links (since SE is built on Zend framework). Checkout http://goo.gl/8Xlak.

        There are 2 choices:

        -Additional database on same host
        -Additional database on remote host.

        I can see both are explained in that guide (I haven’t tried it though). Just note that “application.ini” config should be in “database.php” instead, and from what I’ve read you’ll only need to alter that file in case the other database in on a different host.

        Hope this helps 🙂

  4. Hi Tgalal,
    Will you please contact me at my email? I maybe have some freelance task for you and some ideas for a wiki.

    Thank you!
    Peter

  5. Hi Tarek, well i’ve made a start on the Unofficial SE Dev Knowledgebase site and linked your tutorials there too, http://se4dev.net/socialengine

    Only using WP at the moment (which at least will allow Devs to self-edit/moderate as Authors/Editors) but it’s a start. Your contributions would be very welcome 🙂

    • Great work Clare, I’ll be contributing for sure. I just need some time to pull myself together with all what’s happening here in my country (Egypt).

  6. Clare, sorry I meant to get back to you with a recommendation. I’ve actually got a special WP theme for Wiki’s that I could send you, here’s the site where I purchased it form – http://wpwikitheme.com/ – it uses a special wiki plugin which enables the whole multiple edits and change log that wikis need.

    I’ll have a check tomorrow and see if the plugin has been updated for WP3.0.4 and then send it over to you. 😉

  7. Sounds good Steve, i’ll look into it also 😉

  8. About the $_rowClass property:

    We are actually asking the framework to the row class we want Zend_Db_Table to use. When Zend_Db_Table populates its rows, it will use the User_Model_Friendslist class. This then enables us to put row level functionality into the row classes, meaning we can have smart objects rather than just dumb data containers.

  9. Good article but it could be more accurate.

    • Well any suggestions/ improvements are welcome 🙂 I’m writing those guides while I’m learning how SE works so some info might not be very accurate.

  10. Hi,
    i am new to SocialEngine but i know php very well, so i want implement my own modules for SocialEngine , please can any one will help me, just i want know the steps to create, with simple(hello world) example, it should display hello world on sidebar.

    Thanks in advance

    • Hey mahesh, sorry for the late reply. I’m going to post in 2 days a detailed guide on how to create a module.

  11. Hey tgalal…Thanks for such a greate tips. Well i was wondering about this structure in detail. But you have done so nicely with this flow of giving tips and detailed explanation. I will wait for your other tutorial too.
    Thanks a lot. Well m gonna bookmark this blog and obviously take this site url in my mind. Ha Ha.

    Well I want to know about hooks. How hooks perform in SE4. How can i override some of core functionality with my own functionality.
    For example Comments. I want to override core comment functionality with my new functionaliy without touching the core module. Thats why i want to learn about hooks. How it performs and how it can be created ?

    Sorry for poor english.

    Any help will be greatly appreciable.
    Thanks a lot for such a nice tutorial once again.

    • I’m actually still not familiar with Hooks yet, but try googling “Hooks in Zend” this might help. I’ll post about Hooks if I get familiar with them any time.

    • Thank you for reply…Hope you will get familiar with it soon…however i am trying to hook SE4..if i will get then I will review here…
      Thank You once again…for your nice tutorials…

  12. Good article 🙂
    Thanks

  13. Thank you for the great tutorial! I followed the tutorials in this blog and learned the basics of SE4.

    In case anyone is interested.Now I have written a tutorial covering how to create model, view and controllers files in a custom module and then connect to mySQL to get data and display the obtained data in the view file. Please visit this blog http://chuangyeideas.wordpress.com/2011/08/24/how-to-create-a-model-and-get-data-from-mysql-to-display-in-se4/

  14. Hello,

    This is a burning question and need for me. I can go up to IndexAction of Indexcontroller of SE4. Then I can’t understand which models are used to build the homepage… Any help please? Do u make any email contact with anyone on SE4? In that case I would be interested most.

    Good wishes

    • HELLO, DEAR Moderator,

      I am yet to get the response .

      May I urge you to have a look at my question please?

      Istiaque Ahmed

  15. Thanks for your tutorial, it’s useful. Can you describe the SE database ?

  16. Hi, how do you get the insert id?

  17. could you please write a tutorial about notifications, i want to set notifications custom path how can i do it ?

  18. I found that the model simply refused to link to the table unless I had an auto-incrementing primary key. There might be a way round but I was having a crash out with no errors, so when I found this auto-increment thing I did a lot of air punching.

  19. Hi,
    Thanks for tutorials, but i cant load data from database table.

    When i debug, i noticed that i get table and i can make a select, but a exception is generated when i try fetchAll($select). This code is viewAction of my controller.

    Can you help me please ?

  20. I had made the module traveling …….
    in that i am making the table “engine4_traveling_trips” to store the name of the trips ,photos and so on …
    Bellow is my tripController.php file
    //traveling/controllers/tripController.php
    getDbtable(‘trips’, ‘traveling’);
    // filtering, get only the current user’s trips
    $select = $table->select()
    ->where(“user_id = $id”, 1)
    ->order(‘creation_date’);
    // get the data
    $result = $table->fetchAll($select);
    $this->view->trips = $result;
    }
    }
    ?>

    //traveling/Model/trip.php

    //traveling/Model/DbTable/trips.php

    //traveling/views/scripts/trip/viewall.tpl

    trips as $trip) {
    echo “Trip id is: “.$trip->trip_id.” and trip name is: “.$trip->trip_name.”.”;
    }
    ?>

    When i point my browser to “http://localhost/social/traveling/trip/viewall” it will show the following error…

    We’re sorry!

    We are currently experiencing some technical issues. Please try again or report this to your site administrator using the contact form.

    Administrator: Please check the error log in your admin panel for more information regarding this error.

    Error Code: 2e89dd

    exception ‘Zend_Db_Statement_Mysqli_Exception’ with message ‘Mysqli prepare error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘) ORDER BY `creation_date` ASC’ at line 1′ in C:\xampp\htdocs\social\application\libraries\Zend\Db\Statement\Mysqli.php:77
    Stack trace:
    #0 C:\xampp\htdocs\social\application\libraries\Zend\Db\Statement\Mysqli.php(77): Zend_Db_Statement_Mysqli::_prepare()
    #1 C:\xampp\htdocs\social\application\libraries\Zend\Db\Statement.php(131): Zend_Db_Statement_Mysqli->_prepare()
    #2 C:\xampp\htdocs\social\application\libraries\Zend\Db\Adapter\Mysqli.php(405): Zend_Db_Statement->__construct()
    #3 C:\xampp\htdocs\social\application\libraries\Zend\Db\Adapter\Abstract.php(467): Zend_Db_Adapter_Mysqli->prepare()
    #4 C:\xampp\htdocs\social\application\libraries\Zend\Db\Table\Abstract.php(1509): Zend_Db_Adapter_Abstract->query()
    #5 C:\xampp\htdocs\social\application\libraries\Zend\Db\Table\Abstract.php(1325): Zend_Db_Table_Abstract->_fetch()
    #6 C:\xampp\htdocs\social\application\modules\Traveling\controllers\tripController.php(20): Zend_Db_Table_Abstract->fetchAll(Object(Zend_Db_Table_Select))
    #7 C:\xampp\htdocs\social\application\libraries\Zend\Controller\Action.php(513): Traveling_TripController->viewallAction()
    #8 C:\xampp\htdocs\social\application\libraries\Zend\Controller\Dispatcher\Standard.php(289): Zend_Controller_Action->dispatch(‘viewallAction’)
    #9 C:\xampp\htdocs\social\application\libraries\Zend\Controller\Front.php(946): Zend_Controller_Dispatcher_Standard->dispatch()
    #10 C:\xampp\htdocs\social\application\modules\Core\Bootstrap.php(75): Zend_Controller_Front->dispatch()
    #11 C:\xampp\htdocs\social\application\libraries\Engine\Application.php(160): Core_Bootstrap->run()
    #12 C:\xampp\htdocs\social\application\index.php(205): Engine_Application->run()
    #13 C:\xampp\htdocs\social\index.php(76): include(‘C:\xampp\htdocs…’)
    #14 {main}

    I tried lots of but not get answer plez help me

  21. Hi….i have one doubt with module creation. I have installed one module and that one enabled in module list on admin side. But this module not showing in layout available Block section , like album,Blogs etc…Can you please mention what is the issue here ?

  22. hello,
    i have been using socialengine for small organisation, but i want to add a new feature to it.
    i want to automate the group creation when two parties either of which accepts the friend request.
    I don’t know how to achieve this functionality.Help will really be appreciated.
    Thanks in advance.

  23. Very nice article, This helped me for developing the module for SE4. Now I stuck for inserting a record in a table which does not have table prefix and it has only single name (table name like ‘example’). So now I am inserting it from /plugin/Core.php how can I achieve that?


2 Trackbacks/Pingbacks

  1. […] Creating a Model […]

  2. By Social Engine 4: Modules | My blog on 23 Apr 2015 at 8:41 pm

    […] Creating a Model […]

Leave a reply to Jonesc5 Cancel reply