1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

How to use XF classes/functions in addons?

Discussion in 'XenForo Development Discussions' started by whyweprotest, Jan 20, 2011.

  1. whyweprotest

    whyweprotest Well-Known Member

    Hi all,

    I have noticed a trend in existing addons to do raw SQL queries instead of using built in methods. For example, all of the "Latest Threads" examples do this by using the DB instead of using XF's findNewThreads() function or similar.

    I am mediocre at best at PHP, and absolutely confused when it comes to OOP, but I also couldn't find any threads here about doing this. Is it possible to take this approach? In this example it would make sense because it would allow for the user to only see threads he is permitted to see (vs say, Moderator Chat forums).

    Any pointers would be lovely.

    Thanks!
     
  2. Shadab

    Shadab Well-Known Member

    Reusing existing XenForo model classes is very simple:
    • Call XenForo_Model::create('Your_Model_Class_Name'). This is a static factory method which creates an instance of "Your_Model_Class_Name". Using this method ensures that you wont break any addon which extends this model class.

    • If you are in a controller class, use the getModelFromCache() method, which skips creating a new model object in case its already present in the cache.
    When you are fetching data from models, you'll need to perform any permission checking yourself; either before fetching the data (if you know exactly what content you are fetching, eg. a particular forum record), or after fetching the data (if you cannot possibly know beforehand what content you are fetching, eg. a list of latest threads).

    I posted an example code, which fetches the top X most-liked threads and filters them using the viewing user's permission set: Top Rated Threads - request - code - outside XF.

    But of course, there are times when none of the existing methods in a model return data that you need. That's when you have to create your own model class (standalone, or extending an existing model; your choice). Embedding sql queries directly in a helper, controller or view class is never a good idea. :)
     
    whyweprotest likes this.

Share This Page