Here you will find an ItemManager API overview and some basic examples of how to use it.

The ItemManager library can be used anywhere in your web projects, the API is easy to use and powerful, so working with it is really fun!

Before you start working with ItemManager, you must bootstrap imanager.php in your project. ItemManager library comes with an index.php file in the root directory by default. This file is not needed to run ItemManager and you can safely delete it if you wish. However, if you need some extra API examples, take a look at it, it also provides an example of how to include ItemManager into your script.

include '/your-imanager-location/imanager.php';

Once you have included ItemManager, the API is now available to you in the $imanager global variable, or via the imanager() function. For instance, here's how you would access the systemDateFormat config variable:

echo $imanager->config->systemDateFormat;

The same, by specifying the object as a parameter:

echo imanager('config')->systemDateFormat;

Working with categories

Create a new category:

$category = new \Imanager\Category();
$category->set('name', 'My First Category');
$category->save();

It's also possible to run this task in a chain:

...
$category->set('name', 'My First Category')
         ->save();

Another example, create a category named My Test Category if it does not yet exist:

$category = $imanager->getCategory('name=My Test Category');
if(!$category) {
    $category = new \Imanager\Category();
    $category->set('name', 'My Test Category')
             ->save();
}

Category attributes

You can use any of the following category attributes:

  • name (A string with a maximum length of 255 characters)
  • id (An integer automatically generated when creating categories)
  • position (An integer, if not specified it's created automatically when creating categories)
  • slug (An ASCII string with a maximum length of 255 characters. If not specified it's created automatically from name when creating categories)
  • created (Automatically generated timestamp)
  • updated (Automatically generated timestamp)

To set or change a category attribute value, use Category::set() method:

$category->set('slug', 'my-test-category');

Remember to always save after changing:

$category->save();

To get a specific category, use ItemManager's getCategory() method:

$category = $imanager->getCategory('name=My Test Category');

using the ID:

$category = $imanager->getCategory(1);

using any category attributes:

$category = $imanager->getCategory('slug=my-test-category');

Sometimes you want to apply more complex conditions, such as find a multiple categories created in a certain period of time. To accomplish this you can use the function getCategories(). This function returns an array of objects of type Category, or NULL if no matching categories was found. For example, to select all the categories created within the last week, you can use the method getCategories() repeatedly and pass your results several times through that function:

$now = time();
$lastWeek = $now - (7 * 24 * 60 * 60);
$categories = $imanager->getCategories("created>=$lastWeek");
if($categories) {
    $categories = $imanager->getCategories("created<$now", 0, $categories);
}

You can access category attributes by referencing them from the $category variable directly:

$category = $imanager->getCategory('name=My Test Category');
// Accessing slug
echo "Category Slug: $category->slug<br>";
// Created date
echo 'Created Date: '.date('Y-m-d H:i', $category->created).'<br>';

Create another category:

$category = $imanager->getCategory('name=Another One Category');
if(!$category) {
    $category = new \Imanager\Category();
    $category->set('name', 'Another One Category');
    if($category->save()) {
        echo "A new category named <strong>$category->name</strong> has been created<br>";
    }
}

Delete category

Delete recently created category again (Attention, all related fields, items and its assets are hereby permanently deleted):

$category = $imanager->getCategory('name=Another One Category');
if($category) {
    if($imanager->remove($category)) {
        echo "Category successfully deleted";
    }
}

Working with fields

Create a single field of type text for our category, let's name it url:

$category = $imanager->getCategory('name=My Test Category');
$newField = new \Imanager\Field($category->id);
$newField->set('type', 'text')
         ->set('name', 'url')
         ->set('label', 'Insert any URL')
         ->save();

To see if the field was created correctly, you can use native PHP var_dump() function, or IM's Util::preformat() method, which allows to display formatted object structure:

\Imanager\Util::preformat($category->fields);

The output might look like this:

Array
(
    [url] => Imanager\Field Object
        (
            [categoryid] => 2
            [id] => 1
            [name] => url
            [label] => Insert any URL
            [type] => text
            [position] => 1
            [default] => 
            [options] => Array
                (
                )

            [info] => 
            [required] => 
            [minimum] => 0
            [maximum] => 0
            [cssclass] => 
            [configs] => Imanager\FieldConfigs Object
                (
                )

            [created] => 1516743495
            [updated] => 1516743495
        )
)

If the output works, go on and create more fields for your category: A field of type password with the same name password, and one more text field for storing users first name:

$category = $imanager->getCategory('name=My Test Category');

$newField = new \Imanager\Field($category->id);
$newField->set('type', 'password')
         ->set('name', 'password')
         ->set('label', 'Enter your password here')
         ->save();

$newField = new \Imanager\Field($category->id);
$newField->set('type', 'text')
         ->set('name', 'firstname')
         ->set('label', 'Enter your firstname')
         ->save();

Ok, if you call \Imanager\Util::preformat($category->fields) method, you'll see that you currently have fields listed in the following order:

1. url
2. password
3. firstnanme

Normally it doesn't matter, except that we wanted to build a UI later on, and want to display the fields in the correct order. The order can be changed by adjusting the position of the fields as follows:

$category = $imanager->getCategory('name=My Test Category');

$field = $category->getField('name=firstname');
$field->set('position', 1);
$field->save();

$field = $category->getField('name=password');
$field->set('position', 2);
$field->save();

$field = $category->getField('name=url');
$field->set('position', 3);
$field->save();

It couldn't be easier!

Create another one:

$category = $imanager->getCategory('name=My Test Category');
$newfield = new \Imanager\Field($category->id);

$newfield->set('name', 'test_field');
$newfield->set('type', 'text');
$newfield->save();

If you assign new fields to a category, they are not immediately accessible from existing items. In order to include these fields in the Item object, you must override the existing item first $item->save(). Or you can execute an ItemMapper rebuild() method to overwrite all items of the category at once:

$imanager->itemMapper->rebuild($category_id);

Delete fields

Note: If the config variable $config->backupFields is set to false, deleted fields cannot be restored. Also, all items containing this field will also be modified, the assets (images, files) of these items will not be backed up. If you want to prevent the assets from being deleted, pass false as a second parameter to the function:

$category = $imanager->getCategory('name=My Test Category');

$field = $category->getField('name=test_field');
if($field) {
    $bool = $category->remove($field);
    // Called with a second argument to remove inclusive of the assets
    // $bool = $category->remove($field, $completely = false);
}

Field attributes

All fields contain these built-in attributes, which you can access any time:

  • categoryid (An integer, generated when creating field)
  • id (An integer automatically generated when creating field)
  • name (An ASCII unique string with a maximum length defined in $config->maxFieldNameLength variable. No spaces, hyphens or periods are allowed except underscores)
  • label (UTF-8 string)
  • type (see Field Types)
  • position (An integer, if not specified it's created automatically when creating field)
  • default (A default field value, NULL if not specified)
  • options (An array of field options, used by certain fields)
  • required (Boolean, default FALSE)
  • minimum (Integer, minimum field value length)
  • maximum (Integer, maximum field value length)
  • cssclass (String)
  • configs (FieldConfigs Object, used to customize field configs)
  • created (Automatically generated timestamp)
  • updated (Automatically generated timestamp)

Field types

These field types are currently available:

  • text (Standard text field with a maximum length of 255 characters, but can also be used for longer texts)
  • slug (Address of a specific page or post, with a max len. 250 characters, can't include special characters other than dashes -)
  • password (Special field for storing passwords)
  • longtext (A field for storing longer textes, a CKEditor can also be used)
  • hidden (An alias of text field with a little FieldHidden class exception)
  • fileupload (File or image upload field)
  • dropdown (Dropdown/select field)
  • array (For storing any number of values)
  • checkbox (Checkbox)

Working with items

Items includes both built-in attributes, which are common to all items and custom fields. The custom fields are those that you create manually and then assign to your category. Items also has several functions/methods that enable you to perform other tasks with it.

Let's start right away by creating a few items in our My Test Categorycategory:

// Get the category by name
$category = $imanager->getCategory('name=My Test Category');

// Create new item in your category
$item = new \Imanager\Item($category->id);
// Set name
$item->set('firstname', 'Annamae');
$item->set('url', 'http://annamae-homepage.com');
// Set pass
$result = $item->set('password', array(
        'password' => 'My secret password',
        'confirm_password' => 'My secret password'
    )
);
// Make sure that password is set correctly, then save
if($result !== true) {
    echo "Error code: $result<br>";
} else {
    if($item->save()) {
        echo "User $item->firstname is successfully saved!<br>";
    }
}

// Ok let's create another user
$item = new \Imanager\Item($category->id);
$item->set('firstname', 'Caden');
$item->set('url', 'http://cadens-page.org');
$result = $item->set('password', array(
        'password' => 'Blab',
        'confirm_password' => 'Blab'
    )
);
if($result !== true) {
    echo "Error code: $result<br>";
} else {
    if($item->save()) {
        echo "User $item->firstname is successfully saved!<br>";
    }
}

The method $category->getItem('firstname=Annamae') retrieves an item with the first name Annamae:

$category = $imanager->getCategory('name=My Test Category');
if($category) {
    $item = $category->getItem('firstname=Annamae');
    \Imanager\Util::preformat($item);
}

The output could then look like this:

Imanager\Item Object
(
    [categoryid] => 2
    [id] => 1
    [name] => 
    [label] => 
    [position] => 1
    [active] => 
    [created] => 1516817566
    [updated] => 1516817566
    [firstname] => Annamae
    [url] => http://annamae-homepage.com
    [password] => Imanager\PasswordFieldValue Object
        (
           'password' => '$2y$10$4Owc/PzPRi9nsaPocx134uWl.QiXcSe7jq9W/MmSBPgPwqEnU9bLW',
            ...
        )
)

Accessing fields/attributes

Access the custom fields, for example:

...
$item = $category->getItem('firstname=Annamae');
if($item) {
    echo "User name: $item->firstname<br>";
    echo "User's website: $item->url<br>";
}

Retrieving items | Creating multiple items

There are several methods that could be used for retrieving items. By the way, all of these get* methods always work in the same way for categories, fields or items, but they may have a slightly different names. This means that you only have to remember them once and can use them in the same way in another context. We shall now add a few more items to our category, so we can look at the differences in these methods. Creating the multiple items is easiest done, in a loop:

$users = array(
    array(
        'name' => 'J. Wright',
        'firstname' => 'Daisey',
        'active' => true,
        'url' => 'http://infocpnsan.com'
    ),
    array(
        'name' => 'Lopez',
        'firstname' => 'Glenda',
        'active' => true,
        'url' => 'http://ggmrk.com'
    ),
    array(
        'name' => 'Perković',
        'firstname' => 'Kristijan',
        'active' => true,
        'url' => 'http://metaldefense.com'
    ),
    array(
        'name' => 'Altman',
        'firstname' => 'Michal',
        'active' => true,
        'url' => 'http://fripstorexp.com'
    ),
    array(
        'name' => 'Esselink',
        'firstname' => 'Toon',
        'active' => false,
        'url' => 'https://adoptingsafe.com'
    ),
);

$category = $imanager->getCategory('name=My Test Category');
if($category) {
    foreach($users as $user) {
        // Create new item
        $item = new \Imanager\Item($category->id);
        $item->set('name', $user['name'])
             ->set('firstname', $user['firstname'])
             ->set('url', $user['url'])
             ->set('active', $user['active']);
        if($item->save()) {
            echo "A new user '$item->firstname' has been created<br>";
        }
    }
}

Well, let's select all users who haven't been activated yet i. e. have value of the active attribute set to false. If you want to check the boolean field set to false, you have to use one of the following selectors, which you pass to the $category->getItems() method:

$items = $category->getItems('active!='.true);

Another one selector with empty value:

$items = $category->getItems('active=');

Or by using false in selector value:

$items = $category->getItems('active='.false);

So, if you're going to select the disabled users, do it this way:

$category = $imanager->getCategory('name=My Test Category');
if($category) {
    $users = $category->getItems('active=');
}
...

The function returns an array of objects of type Item, or NULL if no matching items was found.

However, If you only want to select users that have already been activated, proceed as follows:

$category = $imanager->getCategory('name=My Test Category');
if($category) {
    $users = $category->getItems('active='.true);
    // That would work too:
    //$users = $category->getItems('active=1');
}
...

As with the getCategories() method described above, you can use the getItems() method to create more complex queries. So you can call this method repeatedly in order to filter the results more than once. A weird example maybe, if you want to select a specific user with an id between 3 and 5, you can use the $category->getItems() method as follows:

$category = $imanager->getCategory('name=My Test Category');
if($category) {
    $users = $category->getItems('id>3');
    if($users) {
        $users = $category->getItems('id<5', 0, $users);
    }
}

Let's look at another example, say we have a list of vehicles, something like that:

1 => 
  Imanager\Item::__set_state(array(
     ...
     'marke' => 'Honda',
     'model' => 'Civic',
     'specification' => 'Sedan LX',
     'manufacturing' => '2017-07-14',
     'mileage' => '50,671',
  )),
  2 => 
  Imanager\Item::__set_state(array(
    ...
     'marke' => 'Honda',
     'model' => 'Civic',
     'specification' => 'Hatchback LX',
     'manufacturing' => '2018-04-07',
     'mileage' => '20,345',
  )),
  3 => 
  Imanager\Item::__set_state(array(
     ...
     'marke' => 'Honda',
     'model' => 'Civic',
     'specification' => 'Sedan Touring',
     'manufacturing' => '2019-02-08',
     'mileage' => '5,992',
  )),
  4 => 
  Imanager\Item::__set_state(array(
     ...
     'marke' => 'Honda',
     'model' => 'Civic',
     'specification' => 'Hatchback Sport Touring',
     'manufacturing' => '2018-11-03',
     'mileage' => '6,467',
  )),
  5 =>
  Imanager\Item::__set_state(array(
   ...
    'marke' => 'Honda',
    'model' => 'Civic',
    'specification' => 'Hatchback LX',
    'manufacturing' => '2018-05-17',
    'mileage' => '18,148',
   )),

Now, if you want to get all the Honda Civic with Hatchback and year of construction until December 2019, you can use the following code:

    $result = $vehicles->getItems('marke=Honda');
    $result = $vehicles->getItems('model=Civic', 0, $result);
    $result = $vehicles->getItems('specification=Hatchback%', 0, $result);
    $result = $vehicles->getItems('manufacturing<2018-12', 0, $result);

Of course, you can build a function for it, which can make the search easier for you:

function get_vehicles(\Imanager\Category $vehicles, array $selectors, $items = null) 
{
    foreach($selectors as $selector) {
        if(!$items) return null;
        $items = $vehicles->getItems($selector, 0, $items);
    }
    return $items;
}

This is how you can call the function:

// Get vehicles category
$category = $imanager->getCategory('name=vehicles');
// Build your search selector values
$selectors = [
    'marke=Honda',
    'model=Civic',
    'specification=Hatchback%',
    'manufacturing<2018-12'
];
// and search
$vehicles = get_vehicles($category, $selectors, $category->items);

The getItems() method provides a limit as the second parameter, that is used to specify the number of items to return. You may also specify a 0 in the second parameter, where 0 representing the unlimited items number. If an item array is passed as a third parameter, this method performs the search only with item objects contained in this array.

Be careful when selector value is an integer, for instance, this query will return an item with the id 5:

$users = $category->getItems('id=5');

But this selector, too:

$users = $category->getItems('id=5string');

If mathematical/logical operators should be used, you must always check first if this is a numeric value:

$val = '5string';
if(is_int($val)) {
    $users = $category->getItems("id=$val");
}

What is the difference between getItem() and getItems() respectively getCategory() and getCategories() methods? The return value of these two methods differ in the type. As the methods with the ending s returns an array or NULL if no matching, the methods without s returns a single Item or Category object, or NULL if no matching items was found. The methods getItem() and getCategory() does not support the comparison operators like: >, >=, <=. However, you can use the following operators: = or %.

getItems() and getCategories() supported selector operators:

=      Equal to
!=     Not equal to
<      Less than
>      Greater than
<=     Less than or equal to
>=     Greater than or equal to
%word  Contains the exact word or phrase at the beginning of the field
word%  Contains the exact word or phrase at the end of the field
%word% Contains the exact word or phrase

getItem() and getCategory() supported selector operators:

=      Equal to
%word  Contains the exact word or phrase at the beginning of the field
word%  Contains the exact word or phrase at the end of the field
%word% Contains the exact word or phrase

Sorting items and categories

Let's have a look at the method sort(). There are two types of: $category->sort() for sorting items and the parent method $imanager->sort() for sorting both items and categories. They are both equal:

// Sorts items or categories
$result = $imanager->sort($sortby, $order, $offset, $length, $objects);
// Sorts items
$result = $category->sort($sortby, $order, $offset, $length, $items);
  1. $sortby - Item/Category attribute (default position)
  2. $order - ASC or DESC for descending order (default ASC)
  3. $offset - The starting result (0 by default)
  4. $length - The number of returned results for pagination
  5. $items - An array of Item/Category objects you want to sort

You can use getItems(), getCategories() and sort() in conjunction with ItemManager's paginate() to paginate the results (more on this later).

Permanently delete an item and its assets

Note: If the config variable $config->backupItems is set to false, the deleted items cannot be restored. However, even if the $config->backupItems variable is set to true, the assets (images, files) of this item will not be backed up. If you want to prevent the assets from being deleted, pass false as a second parameter to the function:

// Example: Delete a user
$category = $imanager->getCategory('name=My Test Category');
if($category) {
    $user = $category->getItem(3);
    $bool = $category->remove($user);
    // Use "false" if you do not want to delete assets
    // $bool = $category->remove($user, false);
}
...

Returns true on success, or false if the deletion failed.

Built-in attributes of an Item object

  • categoryid (Category id of the item, integer)
  • id (Item id, integer value)
  • name (UTF-8 string)
  • label (UTF-8 string)
  • position (Item's sorting position, integer)
  • active (Boolean)
  • created (Automatically generated timestamp)
  • updated (Automatically generated timestamp)