PHP code example of ikkez / f3-cortex

1. Go to this page and download the library: Download ikkez/f3-cortex library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ikkez / f3-cortex example snippets


// SQL - MySQL
$db = new \DB\SQL('mysql:host=localhost;port=3306;dbname=MyAppDB','user','pw');
// SQL - SQlite
$db = new \DB\SQL('sqlite:db/database.sqlite');
// SQL - PostgreSQL 
$db = new \DB\SQL('pgsql:host=localhost;dbname=MyAppDB','user','pw');
// SQL - SQL Server 
$db = new \DB\SQL('sqlsrv:SERVER=LOCALHOST\SQLEXPRESS2012;Database=MyAppDB','user','pw');
// Jig
$db = new \DB\Jig('data/');
// Mongo
$db = new \DB\Mongo('mongodb://localhost:27017','testdb');

$user = new \DB\Cortex($db, 'users');
$user->name = 'Jack Ripper';
$user->mail = '[email protected]';
$user->save();

$user->load(['mail = ?','[email protected]']);
echo $user->name; // shouts out: Jack Ripper

$user->load(['name like ? AND (deleted = 0 OR rights > ?]', 'Jack%', 3));

Array (
    [0] => (isset(@name) && preg_match(?,@name)) AND ( (isset(@deleted) && (@deleted = 0)) OR (isset(@rights) && @rights > ?) )
    [1] => /^Jack/
    [2] => 3
)

Array (
    [$and] => Array (
        [0] => Array (
            [name] => MongoRegex Object (
                    [regex] => ^Jack
        )   )
        [1] => Array (
            [$or] => Array (
                [0] => Array (
                    [deleted] => 0
                )
                [1] => Array (
                    [rights] => Array (
                        [$gt] => 3
                    )
)))))

$user = new \DB\Cortex($db, 'users', TRUE);
$user->name = 'John';            // varchar(256)
$user->age = 25;                 // integer
$user->active = true;            // boolean|tinyint
$user->lastlogin = '2013-08-28'; // date

// file at app/model/user.php
namespace Model;

class User extends \DB\Cortex {
  protected
    $db = 'AppDB1',     // F3 hive key of a valid DB object
    $table = 'users';   // the DB table to work on
}

$user = new \Model\Users();

// file at app/model/user.php
namespace Model;

class User extends \DB\Cortex {

  protected
    $fieldConf = [
        'name' => [
            'type' => 'VARCHAR256',
            'nullable' => false,
        ],
        'mail' => [
            'type' => 'VARCHAR128',
            'index' => true,
            'unique' => true,
        ],
        'website' => [
            'type' => 'VARCHAR256'
        ],
        'rights_level' => [
            'type' => 'TINYINT',
            'default' => 3,
        ],
    ],
    $db = 'DB',
    $table = 'users',
    $primary = 'id';    // name of the primary key (auto-created), default: id
}

'type' => \DB\SQL\Schema::DT_TIMESTAMP,
'default' => \DB\SQL\Schema::DF_CURRENT_TIMESTAMP,

'colors' => [
    'type' => self::DT_JSON,
],

$mapper->colors = ['red','blue','green'];

class User extends \DB\Cortex {

    function __construct() {
        // get the DB from elsewhere
        $this->db = \Registry::get('DB');
        $f3 = \Base::instance();
        // load fields from .ini file
        if (!$f3->exists('usermodel'))
            $f3->config('app/models/usermodel.ini');
        foreach ($f3->get('usermodel') as $key => $val)
            $this->{$key} = $val;
        parent::__construct();
    }
}

\Model\User::setup();

$fields = [
    'name' => ['type' => \DB\SQL\Schema::DT_TEXT],
    'mail' => ['type' => \DB\SQL\Schema::DT_INT4],
    'website' => ['type' => \DB\SQL\Schema::DT_INT4],
];
\DB\Cortex::setup($db, 'users', $fields);

// With Model class
\Model\User::setdown();

// Without Model class
\DB\Cortex::setdown($db, 'users');

'realTableField' => [
    'relationType' => '\Namespace\ClassName',
],

'virtualField' => [
    'relationType' => ['\Namespace\ClassName','foreignKey'],
],

'tags' => [
    'has-many' => [\Model\Tag::class,'news','news_tags'],
],

'tag_key' => [
    'type' => \DB\SQL\Schema::DT_VARCHAR128,
],
'tags' => [
    'has-many' => [\Model\Tag::class,'news','news_tags',
        'localKey' => 'tag_key'
    ],
],

'tags' => [
    'has-many' => [\Model\Tag::class,'news','news_tags',
        'relPK'=> 'news_id'
    ],
],

'tags' => [
    'has-many' => [\Model\Tag::class,'news','news_tags',
        'relField' => 'news_id'
    ],
],

'news' => [
    'has-many' => [\Model\News::class,'tags','news_tags',
        'relField' => 'tag_id'
    ],
],

// load a specific author
$author = new \AuthorModel();
$author->load(['_id = ?', 2]);

// create a new profile
$profile = new ProfileModel();
$profile->status_message = 'Hello World';

// link author and profile together, just set the foreign model to the desired property 
$profile->author = $author;
 
// OR you can also just put in the id instead of the whole object here 
// (means you don't need to load the author model upfront at all)
$profile->author = 23;
 
$profile->save();

// create a new profile
$profile = new ProfileModel();
$profile->status_message = 'Hello World';
$profile->save();

// load a specific author and add that profile
$author = new \AuthorModel();
$author->load(['_id = ?', 2]);
$author->profile = $profile;
$author->save();

$author->load(['_id = ?', 23]);
echo $author->profile->status_message; // Hello World

$profile->load(['_id = ?', 1]);
echo $profile->author->name; // Johnny English

$author->load(['name = ?','Johnny English']);
$news->load(['_id = ?',42]);
$news->author = $author; // set the object or the raw id
$news->save();

echo $news->author->name; // 'Johnny English'

$author->load(['_id = ?', 42]);
$author->news; // is now an array of NewsModel objects

// if you like to cast them all you can use
$allNewsByAuthorX = $author->castField('news'); // is now a multi-dimensional array

$news->load(['_id = ?',1]);

// array of IDs from TagModel
$news->tags = [12, 5];
// OR a split-able string
$news->tags = '12;5;3;9'; // delimiter: [,;|]
// OR an array of single mapper objects
$news->tags = [$tag,$tag2,$tag3];
// OR a hydrated mapper that may contain multiple results
$tag->load(['_id != ?',42]);
$news->tags = $tag;

// you can also add a single tag to your existing tags
$tag->load(['_id = ?',23]);
$news->tags[] = $tag;

$news->save();

$news->load(['_id = ?',1]);
echo $news->tags[0]['title']; // Web Design
echo $news->tags[1]['title']; // Responsive

$tags->load(['title = ?','Responsive']);
echo $tags->news[0]->title; // '10 Responsive Images Plugins'

$news->tags = [4,7]; // IDs of TagModel
$news->save();

$news->load(['_id = ?', 77]);
echo $news->tags[0]->title; // Web Design
echo $news->tags[1]->title; // Responsive

namespace Model;
class User extends \DB\Cortex {
  protected $fieldConf = [
    'friends' => [
      'has-many' => [\Model\User::class,'friends']
    ]
  ];
}

'friends' => [
  'has-many' => [\Model\User::class,'friends',
    'selfRefField' => 'friends_ref'
  ]
]

$userA = new \Model\User();
$userA->load(['_id = ?', 1]);

$userB = new \Model\User();
$userB->load(['_id = ?', 2]);

$userC = new \Model\User();
$userC->load(['_id = ?', 3]);

if ($userA->friends)
	$userA[] = $userB;
else 
	$userA = [$userB];
	
$userA->save();

$userC->friends = [$userA,$userB];
$userC->save();

$userA->load(['_id = ?', 1]);
$userA->friends->getAll('_id'); // [2,3]
$userB->load(['_id = ?', 2]);
$userB->friends->getAll('_id'); // [1,3]
$userC->load(['_id = ?', 3]);
$userC->friends->getAll('_id'); // [1,2]

$mapper->onload(function($self){
	// custom code
});
// or 
$mapper->onload('App/Foo/Bar::doSomething');

$mapper->onset('field',function($self, $val){
	return md5($val);
});

class User extends \DB\Cortex {
    // [...]
        
    // validate email address
    public function set_mail($value) {
        if (\Audit::instance()->email($value) == false) {
            // no valid email address
            // throw exception or set an error var and display a flash message
            $value = null;
        }
        return $value;
    }    
    // hash a password before saving
    public function set_password($value) {
        return \Bcrypt::instance()->hash($value);
    } 
    public function get_name($value) {
        return ucfirst($value);
    }  
}

$user->password = 'secret';
$user->mail = '[email protected]';

	$fruits = $fruitModel->find(['taste = ?','sweet']);
	$result = $userModel->find(['favorite_fruit IN ?',$fruits])
	

// Contracts fieldConf:
'user' => ['belongs-to-one' => UserModel::class]

// User fieldConf:
'contracts' => ['has-many' => [ContractsModel::class,'user']]

$contracts = new Contracts();
$res = $contracts->paginate(0,10,null, ['order'=>'@user.name ASC']);

$news->has('tags', ['title = ?','Responsive']);
$results = $news->find();
echo $results[0]->title; // '10 Responsive Images Plugins'

$news->has('tags', ['title = ?','Responsive']);
$news->has('author', ['username = ?','ikkez']);
$results = $news->find(['published = ?', 1], ['limit'=>3, 'order'=>'date DESC']);

$author->filter('news', ['date > ?','2014-01-01']);
$author->load(['username = ?', 'ikkez']);

$author->filter('news.tags', ['title = ?','Responsive']);
$author->find();

$author->has('news.tags', ['title = ?','Responsive']);
$author->find();

// find all tags with the sum of all news that uses the tag, ordered by the top occurring tags first.
$tag = new \Model\Tag();
$tag->countRel('news');
$result = $tag->find(null,['order'=>'count_news DESC, title']);

// just set a simple value
$user->virtual('is_online', TRUE);
// or use a callback function
$user->virtual('full_name', function($this) {
	return $this->name.' '.$this->surname;
});

$mapper->newField = 'SQL EXPRESSION';

protected $fieldConf = [
    'fieldName' => [
        'type' => string
        'nullable' => bool
        'default' => mixed
        'index' => bool
        'unique' => bool
    ]
]

bool load([ array $filter = NULL [, array $options = NULL [, int $ttl = 0 ]]])

$user->load(['username = ?','jacky']);
if (!$user->dry()) {
    // user was found and loaded
    echo $user->username;
} else {
    // user was not found
}

int loaded()

$user->load(['last_name = ?','Johnson']);
echo $user->loaded(); // 3

$user->load(['last_name = ?','Johnson']);
echo $user->loaded(); // 3
echo $user->_id; // 1
$user->last();
echo $user->_id; // 3
echo $user->prev()->_id; // 2
echo $user->first()->_id; // 1
echo $user->skip(2)->_id; // 3

array cast ([ Cortex $obj = NULL [, int $rel_depths = 1]])

$data = $item->cast(null,[
    '_id',
    'order.number',
    'product._id',
    'product.title',
    'product.features._id',
    'product.features.title',
    'product.features.icon',
]);

$user->load(['_id = ?',3]);
var_dump($user->cast());
/* Array (
    [_id] => 3
    [first_name] => Steve
    [last_name] => Johnson
    [comments] => Array(
        [1] => Array (
            [_id] = 23
            [post] => 2
            [message] => Foo Bar
        ),
        [2] => Array (
            [_id] = 28
            [post] => 3
            [message] => Lorem Ipsun
        )
    )
)*/

var_dump($user->cast(NULL, 2));
/* Array (
    ...
    [comments] => Array(
        [1] => Array (
            [_id] = 23
            [post] => Array(
                [_id] => 2
                [title] => Kittenz
                [text] => ... 
            )
            [message] => Foo Bar
        ),
        ...
    )
)*/

$user->cast(NULL, [
  '*' => 0,     // cast all own relations to the given depth, 
                // 0 doesn't cast any relation (default if this key is missing)
  'modelA' => 0,// if a relation key is defined here, modelA is being loaded and casted,
                // but not its own relations, because the depth is 0 for it
  'modelB' => 1,// modelB and all its 1st level relations are loaded and casted
  'modelC' => [...] // you can recursively extend this cast array scheme
]);

// simple sample: only cast yourself and the author model without its childs 
$news->cast(NULL,[
    '*'=>0,
    'author'=>0
]);

// nested sample: only cast yourself, 
// your own author relation with its profile and all profile relations 
$news->cast(NULL,[
    '*'=>0,
    'author'=>[
        '*'=>0,
        'profile'=>1
    ]
]);

array|null castField( string $key [, int $rel_depths = 0 ])

CortexCollection|false find([ array $filter = NULL [, array $options = NULL [, int $ttl = 0 ]]])

// find published #web-design news, sorted by approved user comments
$news->has('tags',['slug = ?','web-design']);
$news->filter('comments', ['approved = ?',1]);
$news->countRel('comments');
$records = $news->find(
	['publish_date <= ? and published = ?', date('Y-m-d'), true],
	['order' => 'count_comments desc']
);

CortexCollection findByRawSQL( string|array $query [, array $args = NULL [, int $ttl = 0 ]])

$news_records = $news->findByRawSQL('SELECT * from news where foo <= ? and active = ?',[42, 1]);

Cortex|false findone([ array $filter = NULL [, array $options = NULL [, int $ttl = 0 ]]])

array|null find([ array $filter = NULL [, array $options = NULL [, int $ttl = 0 [, int|array $rel_depths = 1 ]]]])

null addToCollection( CortexCollection $cx )

callback onload( callback $func )

callback onget( string $field, callback $func )

null clear( string $key )

mixed initial( string $key )

null clearFilter([ string $key = null ])

null compare( array $fields, callback $new [, callback $old = null ])

$uploads=[
    'profile_image' => 'temp_uploads/thats_me.jpg',
    'pictures' => ['7bbn4ksw8m5', 'temp_uploads/random_pic.jpg']
];
$this->model->compare($uploads,function($filepath) {
    // new files
    return $this->handleFileUpload($filepath);
}, function($fileId){
    // old files
    $this->deleteFile($fileId);
});

null copyfrom( string|array $key [, callback|array|string $fields = null ])

$news->copyfrom('POST','title;text');

$news->copyfrom('POST',['title','text']);

$news->copyfrom('POST',function($fields) {
    return array_intersect_key($fields,array_flip(['title','text']));
});

null copyto( string $key [, array|string $relDepth = 0 ])

null copyto_flat( string $key )

null count([ array $filter [, array $options = NULL [, int $ttl = 60 ]]])

null countRel( string $key [, string $alias [, array $filter [, array $option]]])

$tags = new \Model\Tag();
$tags->filter('news',['published = ? and publish_date <= ?', true, date('Y-m-d')]);
$tags->countRel('news');
$result = $tags->find(['deleted = ?',0], ['order'=>'count_news desc']);

// fetch all posts, with comments and count its likes (reactions of type "like") on each comment
$post->countRel('comments.reaction','count_likes', ['type = ?', 'like']);
$results = $post->find();

string dbtype()

array defaults([ bool $set = FALSE ])

bool dry()

$mapper->load(['_id = ?','234']);
if ($mapper->dry()) {
    // not found
} else {
    // record was loaded
}

null erase([ array $filter = null ])

$user->erase(['deleted = ?', 1]);

$user->load(['_id = ?',6]);
$user->erase();

bool exists( string $key [, bool $relField = false ])

array fields([ array $fields = [] [, bool $exclude = false ])

var_dump( $user->fields() );
/* Array(
    '_id'
    'username'
    'password'
    'email'
    'active'
    'deleted'
)*/
php
Cortex filter( string $key [, array $filter = null [, array $options = null ]])
php
mixed getRaw( string $key )
php
array|null getFieldConfiguration()
php
string getTable()
php
Cortex has( string $key [, array $filter = null [, array $options = null ]])
php
mixed initial( string $key )
php
$filter1 = ['_id = ?', 999];
$filter2 = ['published = ? or active = ?', true, false];

$new_filter = $mapper->mergeFilter([$filter1, $filter2]);
// array('(_id = ?) and (published = ? or active = ?)', 999, true, false)
php
array paginate([ int $pos = 0 [, int $size = 10 [, array $filter = NULL [, array $options = NULL [, int $ttl = 0 ]]]]])
php
Cortex rel( string $key )
php
$user->load();
var_dump($user->comments); // array of comments
$new_comment = $user->rel('comments'); 
// $new_comment is a new empty \Model\Comment
php
null reset([ bool $mapper = true ])
php
null resetFields( array $fields )
php
array resolveConfiguration()
php
mixed set( string $key, mixed $val )
php
null setdown([ object|string $db = null [, string $table = null ]])
php
null setFieldConfiguration( array $config )
php
bool setup([ object|string $db = null [, string $table = null [, array $fields = null ]]])
php
null touch( string $key [, int $timestamp = NULL ])
php
$mapper->load(['_id = ?','234']);
if ($mapper->valid()) {
    // record was loaded
} else {
    // not found
}
php
null virtual( string $key, mixed $val )
php
$user->virtual('pw_unsecure', function($this) {
    return \Bcrypt::instance()->needs_rehash($this->password, 10);
});
php
null add( Cortex $model )
php
$news->load();
$new_comment = $news->rel('comments');
$new_comment->text = 'Foo Bar';
$news->comments[] = $new_comment;
$news->save();
php
array castAll([ $reldepths = 1 ])
php
$result = $news->find(['published = ?',true]);
if ($result)
    $json = json_encode($result->castAll());
php
array compare( array|CortexCollection $stack [, string $cpm_key = '_id'])
php
$res = $user->friends->compare($newFriendIds);
if (isset($res['old'])) {
	// removed friends
}
if (isset($res['new'])) {
	// added friends
	foreach($res['new'] as $userId) {
		// do something with $userId
	}
}
php
if ($user->friends && $user->friends->contains($newFriend)) {
	$f3->error(400,'This user is already your friend');
	return;
}
php
if ($user->blocked_users->contains($currentUserId,'target')) {
	// this user has blocked you
}
php
array expose()
php
CortexCollection factory( array $records )
php
array getAll( string $prop [, bool $raw = false ])
php
array getBy( string $index [, bool $nested = false ])
php
$pages = $page->find();
$pages_by_slug = $pages->getBy('slug');
php
null orderBy( string $cond )
php
array setModels( array $models [, bool $init = true ])
php
null slice( int $offset [, int $limit = null ])