Getting Started

Installation

To install using composer simply use composer create-project --prefer-dist dvicemuse/accretion
You can also download the raw source from github as https://github.com/dvicemuse/accretion

Configuration

Settings

The settings file allows you to set up global settings for use throughout your application with \Config::get('parameter')

Global Functions

Global Model Method

Directory Structure

Controllers

Controllers are files that allow you to interpret data before presenting it to the user or view.

Creating A Controller

Basic Controller


To create a controller, simply create a new file in the /controller folder and name it as the path that you wish to use as a URL.

The below example would be located at /controller/Dashboard.php. This would allow you to use www.example.com/dashboard as a url and would point to the index method before loading the /view/Dashboard/index.php file.



Example:
<?php

	namespace Controller;

	class Dashboard extends \Controller {
		
		public function __construct(){
			return $this;
		}

		public function index(){
			//place code here for the main view
		}
	}
?>

Controller Methods and Views


When a user goes to a url, Accretion routes to the appropriate method then loads the same view if it exists.

For the above example if a user goes to www.example.com/dashboard/login, here is what Accretion will attempt.

  • Try to load /controller/Dashboard.php
  • Call the header.php file if exists
  • Call the sub_header.php file if exists
  • Call the login method in the Dashboard class.
  • Call the sub_footer.php file if exists
  • Call the footer.php file if exists
  • Try to load /view/Dashboard/login.php



For more information on headers/footers and sub_headers/sub_footers see Headers and Footers


Example:
<?php

	namespace Controller;

	class Dashboard extends \Controller {
		
		public function __construct(){
			return $this;
		}

		public function index(){
			//place code here for the main view
		}

		public function login(){
			//place code here for the login view
		}
	}
?>

URLs

Basic url routing


Urls are generated by naming controllers and their methods as well as adding sub controllers.

In the following example there are several urls available and the controller is located in /controller/Admin.php.

  • www.example.com/admin
  • www.example.com/admin/users
  • www.example.com/admin/accounts
  • www.example.com/admin/emails


Example:
<?php

	namespace Controller;

	class Admin extends \Controller {
		
		public function __construct(){
			return $this;
		}

		public function index(){
			//this method will try to load /view/Admin/index.php
		}

		public function users(){
			//this method will try to load /view/Admin/users.php
		}

		public function accounts(){
			//this method will try to load /view/Admin/accounts.php
		}

		public function emails(){
			//this method will try to load /view/Admin/emails.php
		}
	}
?>

Sub controller url routing


Sometimes a single controller can get pretty large and have many sections that might want to be grouped together with a url. For this we have sub controllers.

The following example shows how to create a sub controller and call it using the url www.example.com/admin/notifications/latest


In this example the controller exists in /controller/Admin/Notifications.php
and a view exists in /view/Admin/Notifications/latest.php



Example:
<?php

	//USE THE NAMESPACE OF THE PARENT CONTROLLER
	namespace Controller\Admin;

	class Notifications extends \Controller\Admin {
		
		public function __construct(){

			//CALL THE PARENT CONSTRUCTOR TO ADOPT ITS PROPERTIES
			parent::__construct();

			return $this;
		}

		public function index(){
			//this method will try to load /view/Admin/Notifications/index.php
		}

		public function latest(){
			//this method will try to load /view/Admin/Notifications/latest.php
		}

		
	}
?>

Namespaces


Controller namespaces allow us to create multiple sub controllers with same and identify what context we are using that controller in.

For example lets say the following controllers exist.

  • /controller/Admin.php
  • /controller/Admin/Users.php
  • /controller/Dashboard.php
  • /controller/Dashboard/Users.php

In the above example, there are two controllers named Users and would need to use namespaces to prevent conflicts.


The following table shows how the controllers should be set up.

Path Class Namespace Extends Class
/controller/Admin.php Admin Controller \Controller
/controller/Admin/Users.php Users Controller\Admin \Controller\Admin
/controller/Dashboard.php Dashboard Controller \Controller
/controller/Dashboard/Users.php Users Controller\Dashboard \Controller\Dashboard


The following example is for /controller/Dashboard/Users.php


Example:
<?php

	//USE THE NAMESPACE OF THE PARENT CONTROLLER
	namespace Controller\Dashboard;

	class Users extends \Controller\Dashboard {
		
		public function __construct(){

			//CALL THE PARENT CONSTRUCTOR TO ADOPT ITS PROPERTIES
			parent::__construct();

			return $this;
		}

		public function index(){
			//this method will try to load /view/Dashboard/Users/index.php
		}		
	}
?>

Autoloaders

Basic Autoloading


Autoloaders allow you to set expected parameters in a controller method and have Accretion automatically load the associated model or data into the controller method

In the example below the user method is called and because the method is typehinted with the model type (User), Accretion will automatically load the User Model with the id of 5124 and set both the $user and $this->user variables to the loaded model.


Request URL: www.example.com/admin/user/5124
Controller Path: /controller/Admin.php


Example:
<?php

	//USE THE NAMESPACE OF THE PARENT CONTROLLER
	namespace Controller;

	class Admin extends \Controller {
		
		public function __construct(){

			return $this;
		}

		public function index(){
			//this method will try to load /view/Admin/index.php
		}

		public function user(User $user){

			//BOTH $user AND $this->user ARE AUTOMATICALLY SET

			//this method will try to load /view/Admin/user.php
		}		
	}
?>

Autoloading Get Variables


Autoloaders can read get and post variables to set data.

In the example below the autoloader works exactly the same as the previous example but uses the variable name to identify which url variable to use.


Request URL: www.example.com/admin/user/user_id=5124
Controller Path: /controller/Admin.php


Example:
<?php

	//USE THE NAMESPACE OF THE PARENT CONTROLLER
	namespace Controller;

	class Admin extends \Controller {
		
		public function __construct(){

			return $this;
		}

		public function index(){
			//this method will try to load /view/Admin/index.php
		}

		public function user(User $get_user_id_as_user){

			//BOTH $user AND $this->user ARE AUTOMATICALLY SET

			//this method will try to load /view/Admin/user.php
		}		
	}
?>

Autoloader Parameter Syntax


Autoloaders can also read different get and post variables based on how they are named.


The below examples can also apply to the above Admin controller user method.

Url Parameters Post Data Result
example.com/admin/user/5 (User $user) -- $this->user = User Model
example.com/admin/user/ (User $user = null) -- $this->user = null
example.com/admin/user/user_id=5 (User $get_user_id_as_user) -- $this->user = User Model
example.com/admin/user/?user_id=5 (User $get_user_id_as_user) -- $this->user = User Model
example.com/admin/user/5 ($user_id) -- $this->user_id = 5
example.com/admin/user/ (User $post_user_id_as_user) $_POST['user_id'] = 5 $this->user = User Model
example.com/admin/user/ (User $post__as_user) $_POST = 5 $this->user = User Model
example.com/admin/user/ (User $post_user_ids_in_user_id_as_users) $_POST['user_ids'] = [5,6,7] $this->users = User Models 5,6,7
example.com/admin/user/ (User $post_user_id_as_user_id) $_POST['user_id'] = 5 $this->user_id = 5

Controller Methods

Require Login


Using this method you can restrict access to a controller and all sub controllers if a user is not logged in.


Basic Authentication can be achieved by adding \Controller::require_login(); to the __construct method of any controller.


Example:
<?php 

	namespace Controller;

	class Admin extends \Controller {
		
		public function __construct(){

			//THIS WILL FORCE THE USER TO LOGIN IF THERE IS NO CURRENT USER SESSION
			\Controller::require_login();

			return $this;
		}
	}
?>

Require Login With Variable


Using this method you can restrict access to a controller and all sub controllers based on the logged in user's credentials as long as they meet the criteria.


In the below example we use \Controller::require_login('user_role', 'admin') to only allow access to this controller if the logged in user has the user_role of admin


Example:
<?php 

	namespace Controller;

	class Admin extends \Controller {
		
		public function __construct(){

			//THIS WILL FORCE THE USER TO LOGIN IF THERE IS NO CURRENT USER SESSION
			\Controller::require_login('user_role', 'admin');

			return $this;
		}
	}
?>

Disable Header


This method can be used to turn off header and footer for one or more controller methods.


In the below example we use \Controller::disable_header('user'); to disable the header for the user view only.

In the below example we use \Controller::disable_header(['account','email']); to disable the header for the account and email views.


Example:
<?php 

	namespace Controller;

	class Admin extends \Controller {
		
		public function __construct(){

			//THIS WILL TURN OFF HEADER AND FOOTER FOR THE user VIEW
			\Controller::disable_header('user');

			//THIS WILL TURN OFF THE HEADER AND FOOTER FOR BOTH THE account AND eamil VIEWS
			\Controller::disable_header(['account','email']);

			return $this;
		}

		public function index(){
			//this will load the view /view/Admin/index.php with the header and footer.
		}

		public function user(){
			//this will load the view /view/Admin/user.php without the header or footer.
		}

		public function account(){
			//this will load the view /view/Admin/account.php without the header or footer.
		}

		public function email(){
			//this will load the view /view/Admin/email.php without the header or footer.
		}
	}
?>

Disable Subheader


When this method is called it will force the view to load without a subheader.


In the below example we use \Controller::disable_subheader(); to disable the header for the user view only.


Example:
<?php 

	namespace Controller;

	class Admin extends \Controller {
		
		public function __construct(){

			//THIS WILL FORCE THE USER TO LOGIN IF THERE IS NO CURRENT USER SESSION
			\Controller::require_login();

			return $this;
		}

		public function index(){
			//this will load the view /view/Admin/index.php with the sub header and sub footer if they exist.
		}

		public function user(){

			\Controller::disable_subheader();

			//this will load the view /view/Admin/user.php without the sub header and sub footer.
		}
	}
?>

Format URL


This method can be used to convert a url to a standard lowercase string with dashes instead of underscores. This can be helpful because Accretion will convert urls to this format before routing which means that when a user requests a page they can get to it with different combinations of cases and dashes.


Using \Controller::format_url('www.example.com/Admin/User_Info'); will return www.example.com/admin/user-info.


Views

Views are the pages that are actually output to the browser.

Creating A View



At it's most basic, a view is just html that is loaded after a controller has been called.

In the below example the view is loaded when the user visits www.example.com/dashboard

In the below example the file is located at /view/Dashboard/index.php

Example:
<h1>Hello World!</h1>

Visiting the above url will simply output Hello World! as a h1



Now if we want to pass data to the view we need to use a controller. Lets create a controller.

In the below example the file is located at /controller/Dashboard.php

Example:
<?php 

	namespace Controller;

	class Dashboard extends \Controller {
		
		public function __construct(){

			return $this;
		}

		public function index(){
			$this->output = 'Called From Controller';
		}
	}
?>


Now that we have data passed to the view from the controller, lets call that data.

In the below example the file is located at /controller/Dashboard.php

Example:
<h1><?=$this->output?></h1>

The above example will output 'Called From Controller' as a h1


Headers & Footers

Headers and footers are files that are automatically loaded before and after a view has been loaded.

Basic Header And Footer


The default header is loaded from /view/partial/header.php but this can be overridden by the folder structure.

Lets take a look at a basic header. This header will be loaded from /view/partial/header.php


Example:
<!DOCTYPE html>
<html lang="en">
	<head>
    	<meta charset="utf-8">
    	<title><? View::page_title();?></title>

    	<!-- AUTO LOAD CSS/JS -->
        <? View::auto_header() ?>

	</head>
	<body>
		<div class="main-content">

And below is a basic footer loaded from /view/partial/footer.php

Example:
		
		</div><!-- /.main-content -->
	</body>
</html>

With the above two files, any view that is loaded will be wrapped in the header and footer



There are two View Methods being utilized in the above exampe:

For more information on View Methods check out View Methods
You can disable headers/footers from the controller. To see how check out Controller Methods

Header & Footer Override Templates


A header and/or a footer can be overridden based on its path.

Lets assume that we have a default header and a header that we want to override based on the url.
If both of the below files exist they will change based on the url.

  1. /view/partial/header.php
  2. /view/Dashboard/partial/header.php

If the url www.example.com/ was requested the /view/partial/header.php would be loaded.

But if the url www.example.com/Dashboard was requested the /view/Dashboard/partial/header.php would be loaded.


In the above examples, the same logic applies to both
/view/partial/footer.php
and
/view/Dashboard/partial/footer.php

Sub Headers & Sub Footers


Sometimes you may want to load a header/footer for every view in a group without overriding the entire header and footer. For this reason we have sub headers and sub footers.

Lets assume all of the below files exist.

Controllers:
  • /controller/Dashboard.php

Views:
  • /view/partial/header.php <- default header
  • /view/partial/footer.php <- default footer
  • /view/Dashboard/partial/sub_header.php <- dashboard sub header
  • /view/Dashboard/partial/sub_footer.php <- dashboard sub footer


In the above file structure if the url www.example.com/Dashboard was requested the following would happen:

  1. /controller/Dashboard.php would load and call the index() method
  2. /view/partial/header.php would load.
  3. /view/Dashboard/partial/sub_header.php would load.
  4. /view/Dashboard/index.php would load.
  5. /view/Dashboard/partial/sub_footer.php would load.
  6. /view/partial/footer.php would load.
You can disable sub headers/sub footers from the controller. To see how check out Controller Methods

Multiple Sub Headers & Sub Footers


Sub headers and sub footers will keep loading all the way back to the root structure.

Lets assume all of the below files exist.

Controllers
  • /controller/Dashboard.php
  • /controller/Dashboard/Events.php

Views:
  • /view/partial/header.php <- default header
  • /view/partial/footer.php <- default footer
  • /view/Dashboard/partial/sub_header.php <- dashboard sub header
  • /view/Dashboard/partial/sub_footer.php <- dashboard sub footer
  • /view/Dashboard/Events/partial/sub_header.php <- events sub header
  • /view/Dashboard/Events/partial/sub_footer.php <- events sub footer

In the above file structure if the url www.example.com/Dashboard/Events was requested the following would happen.

  1. /controller/Dashboard/Events.php would load and call the index() method
  2. /view/partial/header.php would load.
  3. /view/Dashboard/partial/sub_header.php would load.
  4. /view/Dashboard/Events/partial/sub_header.php would load.
  5. /view/Dashboard/Events/index.php would load.
  6. /view/Dashboard/Events/partial/sub_footer.php would load.
  7. /view/Dashboard/partial/sub_footer.php would load.
  8. /view/partial/footer.php would load.

Partials

Partials are files that allow you to write code once and reuse it throughout your application easilly.

Basic Partial

Calling a partial can be done from any part of the application using View::partial()

By default a partial assumes you are trying to load from somewhere in the local directory.

Lets assume the following files exist:

Controllers:
  • /controller/Dashboard.php
Views:
  • /view/Dashboard/notifications.php
  • /view/Dashboard/partial/latest_notifications.php
Example:
/view/Dashboard/notifications.php
<p>some content</p>
<? $this->pass_var = 'pass this var'; ?>
<? View::partial('latest_notifications') ?>

Example:
/view/Dashboard/partial/latest_notifications.php
<p>some content loaded from partial</p>
<p><?= $this->pass_var; ?></p>


The above example will output:


some content

some content loaded from partial

pass this var


CSS

CSS Files are autoloaded into the header based on the controller and method used as long as the header used is calling View::auto_header();

To showcase how css files are loaded lets assume the following files exist:

Views
  • /view/Dashboard/index.php
  • /view/Dashboard/users.php
  • /view/Dashboard/Notifications/index.php
  • /view/Dashboard/Notifications/latest.php
CSS
  • /view/Dashboard/css/Dashboard.css
  • /view/Dashboard/css/index.css
  • /view/Dashboard/css/users.css
  • /view/Dashboard/Notifications/css/Notifications.css
  • /view/Dashboard/Notifications/css/index.css
  • /view/Dashboard/Notifications/css/latest.css

The below table shows what css files will be loaded.

URL Loaded CSS Files
www.example.com/Dashboard /view/Dashboard/css/Dashboard.css
/view/Dashboard/css/index.css
www.example.com/Dashboard/users /view/Dashboard/css/Dashboard.css
/view/Dashboard/css/users.css
www.example.com/Dashboard/Notifications /view/Dashboard/css/Dashboard.css
/view/Dashboard/Notifications/css/Notifications.css
/view/Dashboard/Notifications/css/index.css
www.example.com/Dashboard/Notifications/latest /view/Dashboard/css/Dashboard.css
/view/Dashboard/Notifications/css/Notifications.css
/view/Dashboard/Notifications/css/latest.css

Javascript

Javascript Files are autoloaded into the header based on the controller and method used as long as the header used is calling View::auto_header();

To showcase how javascript files are loaded lets assume the following files exist:

Views
  • /view/Dashboard/index.php
  • /view/Dashboard/users.php
  • /view/Dashboard/Notifications/index.php
  • /view/Dashboard/Notifications/latest.php
CSS
  • /view/Dashboard/js/Dashboard.js
  • /view/Dashboard/js/index.js
  • /view/Dashboard/js/users.js
  • /view/Dashboard/Notifications/js/Notifications.js
  • /view/Dashboard/Notifications/js/index.js
  • /view/Dashboard/Notifications/js/latest.js

The below table shows what javascript files will be loaded.

URL Loaded Javascript Files
www.example.com/Dashboard /view/Dashboard/js/Dashboard.js
/view/Dashboard/js/index.js
www.example.com/Dashboard/users /view/Dashboard/js/Dashboard.js
/view/Dashboard/js/users.js
www.example.com/Dashboard/Notifications /view/Dashboard/js/Dashboard.js
/view/Dashboard/Notifications/js/Notifications.js
/view/Dashboard/Notifications/js/index.js
www.example.com/Dashboard/Notifications/latest /view/Dashboard/js/Dashboard.js
/view/Dashboard/Notifications/js/Notifications.js
/view/Dashboard/Notifications/js/latest.js

View Structure

The structure of the view folder can be customized to you needs. Below is an exampe of how views/partials/css/javascript files can be used.
  • /view/Dashboard
    • css
      • Dashboard.css
      • index.css
      • latest.css
      • settings.css
    • js
      • Dashboard.js
      • index.js
      • latest.js
      • settings.js
    • partial
      • nav.php
      • events.php
      • users
        • latest.php
        • basic.php
    • Notifications
      • css
        • Notifications.css
        • index.css
        • history.css
      • js
        • Notifications.js
        • index.js
        • history.js
      • partial
        • nav.php
        • sub_header.php
        • sub_footer.php
      • index.php
      • history.php
    • index.php
    • latest.php
    • settings.php

View Methods

There are several methods available for views through the Accretion Framework.

Get

The get method for the view object allows you to call a view by a name with several options.
Options
  • template - default = false
  • controller - default = false
  • headers - default = true
  • sub_header - default = true
Examples:
Example 1:

Requested URL: www.example.com/Dashboard

View::get()

From the dashboard controller this method will load the index view


Example 2:

Requested URL: www.example.com/Dashboard/users

View::get()

From the dashboard controller this method will load the users view


Example 3:

Requested URL: www.example.com/Dashboard/

View::get('users')

From the dashboard controller this method will load the users view even though the url was not called


Example 4:

Requested URL: www.example.com/Admin/

View::get('users', 'Dashboard')

From the Admin controller this method will load the users view from the Dashboard controller


Example 5:

Requested URL: www.example.com/Admin/

View::get('users', 'Dashboard', false)

From the Admin controller this method will load the users view from the Dashboard controller without the header/footer


Example 6:

Requested URL: www.example.com/Admin/

View::get('users', 'Dashboard', false, false)

From the Admin controller this method will load the users view from the Dashboard controller without the header/footer and will not load the sub_header/sub_footer


Page Title


Page title is a method for guessing what the page title should be based on the url, but it will use the $this->page_title variable if it was set from the controller. (This is generally called from the header file)
Example 1:

The requested url is www.example.com/Dashboard/users

Calling View::page_title() from the requested url will output the following:

Dashboard | Users
Example 2:

The requested url is www.example.com/Dashboard/users

If the variable $this->page_title = 'This is a users page' was set from the controller the output will be:

This is a users page
Setting the page title from a controller example (assumes the controller is located at /controller/Dashboard.php)
<?php

	namespace Controller;

	class Dashboard extends \Controller {

		public function __construct(){
			return $this;
		}

		public function index(){
			//do stuff here
		}

		public function users(){
			$this->page_title = 'This is a users page';
		}
	}
?>
											

Auto Header

The View::auto_header() method autoloads any css and javascript files that were set in the Settings File along with any appropriate css/javascript for the requested controller/view. This method is generally used in the header file

For the following example lets assume a few things:

  • The url requested was www.example.com/Dashboard/users
  • The following files exist.
    • /controller/Dashboard.php
    • /view/Dashboard/users.php
    • /view/Dashboard/css/Dashboard.css
    • /view/Dashboard/css/users.css
    • /view/Dashboard/css/Dashboard.js
    • /view/Dashboard/css/users.js


When the above url is requested the following will occur.

  1. /controller/Dashboard.php will load and a new Dashboard class will be instantiated.
  2. The users() method of the Dashboard class will be executed.
  3. /view/partial/header.php will be loaded.
  4. /view/Dashboard/users.php will be loaded.
  5. /view/partial/footer.php will be loaded.



When /view/partial/header.php is loaded if it has <? View::auto_header(); ?> in the <head> section, it will try to render:

  • <link rel="stylesheet" type="text/css" href="/view/Dashboard/css/Dashboard.css">
  • <link rel="stylesheet" type="text/css" href="/view/Dashboard/css/users.css">
  • <script type="text/javascript" src="/view/Dashboard/js/Dashboard.js"></script>
  • <script type="text/javascript" src="/view/Dashboard/js/users.js"></script>



Eseentially any time you place a css or js file in a folder next to a view with the same name it will be loaded. The controller name will also be loaded.

Dashboard.css is loaded because the controller is Dashboard

users.css is loaded because the method is users

The same logic applies to javascript files



Example:
<!DOCTYPE html>
<html lang="en">
	<head>
    	<meta charset="utf-8">
    	<title><? View::page_title();?></title>

    	<!-- AUTO LOAD CSS/JS -->
        <? View::auto_header() ?>

	</head>
	<body>
		<div class="main-content">

Partial

Partials are files that allow you to write code once and reuse it throughout your application easilly.
Usage:
\View::partial('/path/to/partial', 'path/to/controller');

Basic Partial

Calling a partial can be done from any part of the application using View::partial()

By default a partial assumes you are trying to load from somewhere in the local directory.

Lets assume the following files exist:

Controllers:
  • /controller/Dashboard.php
Views:
  • /view/Dashboard/notifications.php
  • /view/Dashboard/partial/latest_notifications.php
Example:

/view/Dashboard/notifications.php

<p>some content</p>
<? $this->pass_var = 'pass this var'; ?>
<? View::partial('latest_notifications') ?>

Example:

/view/Dashboard/partial/latest_notifications.php

<p>some content loaded from partial</p>
<p><?= $this->pass_var; ?></p>


The above example will output:


some content

some content loaded from partial

pass this var


Partial Directories


A partial can be called from other controllers or even be nested in folders and still called.

Lets assume the following files exist:


Controllers:
  • /controller/Dashboard/Admin.php
  • /controller/Users.php
Views:
  • /view/Dashboard/Admin/partial/users/basic_info.php
  • /view/Users/index.php

Example:

/view/Users/index.php

<p>Some view stuff<p>
<p><? View::partial('users/basic_info', 'Dashboard/Admin'); ?><p>

Example:

/view/Dashboard/Admin/partial/users/basic_info.php

<p>basic info<p>


If the url www.example.com/Users is called the output will be:

Some view stuff

basic info


Make

Occasionally you may need to grab the rendered html from a view. In that case you use the \View::make(); method.
This method acts exactly like the \View::get() method exept that it will return a string containing the html instead of rendering the html to the browser.

Make Partial

Occasionally you may need to grab the rendered html from a partial. In that case you use the \View::make_partial(); method.
This method acts exactly like the \View::partial() method exept that it will return a string containing the html instead of rendering the html to the browser.

CSS

Sometimes you might need to add a css tag to html. The \View::css(); method allows you to intuitively render stylesheets to html.
Options:
  • file_name - required
  • path - false

You can pass a full url to this method or pass just a file name.

If the file name passed is not a url then Accretion will attempt to find the file in the current directory.

If you are trying to load a css file from directory that is not where the current controller is, you can pass a path variable.




Example 1:

If the url www.example.com/Dashboard is requested the following code will try to render
<link rel="stylesheet" type="text/css" href="/view/Dashboard/css/style.css">

<? \View::css('style'); ?>


Example 2:

If the url www.example.com/Dashboard is requested the following code will try to render
<link rel="stylesheet" type="text/css" href="/view/Admin/css/style.css">

<? \View::css('style', 'Admin'); ?>


Example 3:

If the url www.example.com/Dashboard is requested the following code will try to render
<link rel="stylesheet" type="text/css" href="http:://test.com/path/to/stylesheet/style.css">

<? \View::css('http:://test.com/path/to/stylesheet/style.css'); ?>

JS


Sometimes you might need to add a javascript tag to html. The \View::js(); method allows you to intuitively render javascript tags to html.
Options:
  • file_name - required
  • path - false

You can pass a full url to this method or pass just a file name.

If the file name passed is not a url then Accretion will attempt to find the file in the current directory.

If you are trying to load a css file from directory that is not where the current controller is, you can pass a path variable.



Example 1:

If the url www.example.com/Dashboard is requested the following code will try to render
<script type="text/javascript" href="/view/Dashboard/js/script.js"></script>

<? \View::js('script'); ?>


Example 2:

If the url www.example.com/Dashboard is requested the following code will try to render
<script type="text/javascript" href="/view/Admin/js/script.js"></script>

<? \View::js('script', 'Admin'); ?>


Example 3:

If the url www.example.com/Dashboard is requested the following code will try to render
<script type="text/javascript" href="http:://test.com/path/to/script/script.js"></script>

<? \View::js('http:://test.com/path/to/script/script.js'); ?>

Local Template Path


There might be a point when you are developing your application that you need to find what the path of the current view is. This method will return the local path in two different ways.

Options
  • format - default = false


In the following examples the url www.example.com/Admin/Users/user_status/5 was called


Example 1:
<? \View::local_template_path()l ?>
									

The above example will return /Admin/Users/user_status


Example 2:
<? \View::local_template_path(true); ?>
									

The above example will return /admin/users/user-status



Models

Models are a representation of a database table and/or database table record. They can be used to create/read/update/delete (CRUD) parts of the database.

Creating a Model

If you are using the model structure plugin, creating or changing a model's schema will automatically change the database.
All models for your application should live in /model/Model_Name.php
A model's class needs to be named the EXACTLY the same as its file.
Example:
This example model's path is: /model/User.php
<?php
	class User extends Model{

		public $structure = array(
			'user_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'user_first_name' 	=> array('Type' => "varchar(255)"),
			'user_last_name'	=> array('Type' => "varchar(255)",),
			'user_email'		=> array('Type' => "varchar(255)",),
			'user_password'		=> array('Type' => "varchar(255)",),
			'user_role'		=> array('Type' => "enum('user','admin')", 'Default' => "user",),
			'user_create_time'	=> array('Type' => "timestamp", 'Default' => "CURRENT_TIMESTAMP",),
		);

		public function __construct(){

		}
	}
?>
										

In the above example, if the model has never been loaded before and the Model Structure helper is enabled, this model will automatically create the table and the necessary fields.

The above example will reference the user table unless a different table is specified.



Example:
This example model's path is: /model/User.php
<?php
	class User extends Model{

		public $structure = array(
			'user_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'user_first_name' 	=> array('Type' => "varchar(255)"),
			'user_last_name'	=> array('Type' => "varchar(255)",),
			'user_email'		=> array('Type' => "varchar(255)",),
			'user_password'		=> array('Type' => "varchar(255)",),
			'user_role'		=> array('Type' => "enum('user','admin')", 'Default' => "user",),
			'user_create_time'	=> array('Type' => "timestamp", 'Default' => "CURRENT_TIMESTAMP",),
		);

		public $table_name = 'users';

		public function __construct(){

		}
	}
?>
										

In the above example, the model utilizes the property $table_name and names is as users. By default this model would try to load from the table "user" but because the table_name variable is set this model will load from the table "users"

Using Models

Models can be loaded with a variety of methods. \Model::get('User') is the most efficient way to load a model. However, the same model may also be loaded by using \Model::User(); or \User::find();

Lets assume that you want to load a user with a `user_id` of '5'. You can do this several ways.

  1. \Model::get('User')->load(5);
  2. \Model::User(5);
  3. \User::find(5);

The first option above is guarenteed to load the model from anywhere in your application.

The second option calls the first option but does not work when called from within a model but works everywhere else in the framework.

The third option is the easiest to write but does not work when being called from within a model but does work everywhere else.

The only guaranteed ways to load a model are as follows:

  • \Model::get('User');
  • $model = new \User;
    $model = $model->load(5);

Accretion ORM

The Accretion ORM (Object Relational Mapping) is a system that allows you to define complex relationships between models and easilly traverse different sets of data.

The Accretion ORM can be used when loading a model, when calling a model's relationship and when defining a models relationship.

Orm Methods

Where

The where method is the most versatile of the Accretion ORM methods. This method can take an array of options that can include any of the other orm options or simply be a mysql where query.
Example 1:
Load all users with the user_role of 'admin' with the Accretion ORM
$users = \User::find()->where("user_role = 'admin'")->load();
												

The above example will load something simlar to the below example:

Users load by ORM where method response
ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
            [0] => User Object
                (
                    [user_id] => 6112162
                    [user_first_name] => John
                    [user_last_name] => Doe
                    [user_email] => john-doe@gmail.com
                    [user_password] = abafgsdjfkgjlhjlk;afgfgh.jdgghjfkghfgshdjfkg> 
                    [user_role] => admin                    
                )

            [1] => User Object
                (
                    [user_id] => 6519848
                    [user_first_name] => Jane
                    [user_last_name] => Doe
                    [user_email] => jane-doe@gmail.com
                    [user_password] = abafgsdjfkgjlhjlk;afgfgh.jdgghjfkghfgshdjfkg> 
                    [user_role] => admin                    
                )
        )

    [_results:ORM_Wrapper:private] => 
)
												

Order

The order method allows you to pass criteria on how you would like to order your results.
Example 1:
Load all users with the user_role of 'admin' with the Accretion ORM and order the results by the user_id descending.
$users = \User::find()->where("user_role = 'admin'")->order("user_id DESC")->load();
												

The above example will load something simlar to the below example:

Users load by ORM where method response
ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
            [0] => User Object
                (
                    [user_id] => 2
                    [user_first_name] => John
                    [user_last_name] => Doe
                    [user_email] => john-doe@gmail.com
                    [user_password] = abafgsdjfkgjlhjlk;afgfgh.jdgghjfkghfgshdjfkg> 
                    [user_role] => admin                    
                )

            [1] => User Object
                (
                    [user_id] => 1
                    [user_first_name] => Jane
                    [user_last_name] => Doe
                    [user_email] => jane-doe@gmail.com
                    [user_password] = abafgsdjfkgjlhjlk;afgfgh.jdgghjfkghfgshdjfkg> 
                    [user_role] => admin                    
                )
        )

    [_results:ORM_Wrapper:private] => 
)
												

Limit

The limit method allows you to specify how many results you would like to receive.
Example 1:
Load all users with the user_role of 'admin' with the Accretion ORM and order the results by the user_id descending and limit the results to 3 results.
$users = \User::find()->where("user_role = 'admin'")->order("user_id DESC")->limit(3)->load();
												

The above example will load something simlar to the below example:

Users load by ORM where method response
ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
            [0] => User Object
                (
                    [user_id] => 3
                    [user_first_name] => John
                    [user_last_name] => Doe
                    [user_email] => john-doe@gmail.com
                    [user_password] = abafgsdjfkgjlhjlk;afgfgh.jdgghjfkghfgshdjfkg> 
                    [user_role] => admin                    
                )

            [1] => User Object
                (
                    [user_id] => 2
                    [user_first_name] => Jane
                    [user_last_name] => Doe
                    [user_email] => jane-doe@gmail.com
                    [user_password] = abafgsdjfkgjlhjlk;afgfgh.jdgghjfkghfgshdjfkg> 
                    [user_role] => admin                    
                )
            [2] => User Object
                (
                    [user_id] => 1
                    [user_first_name] => Jack
                    [user_last_name] => Doe
                    [user_email] => jack-doe@gmail.com
                    [user_password] = abafgsdjfkgjlhjlk;afgfgh.jdgghjfkghfgshdjfkg> 
                    [user_role] => admin                    
                )
        )

    [_results:ORM_Wrapper:private] => 
)
												

Count

The count method will return the total number of records that should be loaded.
Example 1:
Load all users with the user_role of 'admin' with the Accretion ORM and order the results by the user_id descending and limit the results to 3 results and count the total results.
$users = \User::find()->where("user_role = 'admin'")->order("user_id DESC")->limit(3)->count()->load();
												

The above example will load something simlar to the below example:

Users load by ORM where method response
3

Single

The single method retrieves the first result of any model load request.
Example 1:
Load all users with the user_role of 'admin' with the Accretion ORM and order the results by the user_id descending and get a single result (the first result).
$users = \User::find()->where("user_role = 'admin'")->order("user_id DESC")->single()->load();
												

The above example will load something simlar to the below example:

Users load by ORM where method response
User Object
(
    [user_id] => 3
    [user_first_name] => John
    [user_last_name] => Doe
    [user_email] => john-doe@gmail.com
    [user_password] = abafgsdjfkgjlhjlk;afgfgh.jdgghjfkghfgshdjfkg> 
    [user_role] => admin                    
)

            
												

Paginate

The paginate method will allow you to automatically prepare query results for pagination. For more information on using pagination see System Helpers - Paginate
Example 1:
Load all users with the user_role of 'admin' with the Accretion ORM and order the results by the user_id descending and limit the results to 3 results and count the total results.
$users = \User::find()->where("user_role = 'admin'")->order("user_id DESC")->paginate(20)->load();
												

The above example will a paginate helper object. For More information on paginate helper objects see: System Helpers - Paginate

Only

The only method allows you to just load part of a model based on the field you want to retrieve.
Example 1:
Load all users with the user_role of 'admin' with the Accretion ORM and order the results by the user_id descending and get a single result (the first result) and only retrive the users first name.
$users = \User::find()->where("user_role = 'admin'")->order("user_id DESC")->single()->only('user_first_name')->load();
												

The above example will load something simlar to the below example:

Users load by ORM where method response
User Object
(
    [user_first_name] => John               
)
            
												

Sum

The sum method allows you to add up all of the values of a specific field.
Example 1:
Load all users with the user_role of 'admin' with the Accretion ORM and order the results by the user_id descending and limit the results to 3 results then add up the values of the user_id field.
$users = \User::find()->where("user_role = 'admin'")->order("user_id DESC")->limit(3)->load();
												

The above example will load something simlar to the below example:

Users load by ORM where method response
3

Get Query

The get query method will return the actual sql query that will be used to load this model.
Example 1:
Load all users with the user_role of 'admin' with the Accretion ORM and order the results by the user_id descending and limit the results to 3 results then add up the values of the user_id field.
$users = \User::find()->where("user_role = 'admin'")->order("user_id DESC")->limit(3)->load();
												

The above example will load something simlar to the below example:

Users load by ORM where method response
													
SELECT
	*
FROM
	user
WHERE
	user_role = 'admin'
ORDER BY user_id DESC
LIMIT 3
											

Where Alias

This allows you to specify the table alias you would like to use when running a query.
Example 1:
Load all users with the user_role of 'admin' with the Accretion ORM and order the results by the user_id descending and limit the results to 3 and use the table alias of "u".
$users = \User::find()->where_alias("u")->where("u.user_role = 'admin'")->order("u.user_id DESC")->limit(3)->load();
												

The above example will load something simlar to the below example:

Users load by ORM where method response
ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
            [0] => User Object
                (
                    [user_id] => 3
                    [user_first_name] => John
                    [user_last_name] => Doe
                    [user_email] => john-doe@gmail.com
                    [user_password] = abafgsdjfkgjlhjlk;afgfgh.jdgghjfkghfgshdjfkg> 
                    [user_role] => admin                    
                )

            [1] => User Object
                (
                    [user_id] => 2
                    [user_first_name] => Jane
                    [user_last_name] => Doe
                    [user_email] => jane-doe@gmail.com
                    [user_password] = abafgsdjfkgjlhjlk;afgfgh.jdgghjfkghfgshdjfkg> 
                    [user_role] => admin                    
                )
            [2] => User Object
                (
                    [user_id] => 1
                    [user_first_name] => Jack
                    [user_last_name] => Doe
                    [user_email] => jack-doe@gmail.com
                    [user_password] = abafgsdjfkgjlhjlk;afgfgh.jdgghjfkghfgshdjfkg> 
                    [user_role] => admin                    
                )
        )

    [_results:ORM_Wrapper:private] => 
)
												

Where Join

This allows you to join another table when running a query.
Example 1:
Load all users and try to left join an account based on the user_id field
$users = \User::find()->where_alias("u")->where_join("accounts AS a on a.user_id = u.user_id", "LEFT JOIN")->load();
												

The above example will load something simlar to the below example:

Users load by ORM where method response
ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
            [0] => User Object
                (
                    [user_id] => 0
                    [user_first_name] => John
                    [user_last_name] => Doe
                    [user_email] => john-doe@gmail.com
                    [user_password] = abafgsdjfkgjlhjlk;afgfgh.jdgghjfkghfgshdjfkg> 
                    [user_role] => admin                    
                )

            [1] => User Object
                (
                    [user_id] => 1
                    [user_first_name] => Jane
                    [user_last_name] => Doe
                    [user_email] => jane-doe@gmail.com
                    [user_password] = abafgsdjfkgjlhjlk;afgfgh.jdgghjfkghfgshdjfkg> 
                    [user_role] => admin                    
                )
            [2] => User Object
                (
                    [user_id] => 2
                    [user_first_name] => Jack
                    [user_last_name] => Doe
                    [user_email] => jack-doe@gmail.com
                    [user_password] = abafgsdjfkgjlhjlk;afgfgh.jdgghjfkghfgshdjfkg> 
                    [user_role] => admin                    
                )
        )

    [_results:ORM_Wrapper:private] => 
)
												

Call Hooks

Hooks are ways to run code before or after a model has changed. To learn more about model hooks see. Model Hooks

Using this method makes sure that none of the model hooks are executed after a change to the model.

Example:
$this->call_hooks(false)

Relationships

Model relationships are methods by which you can call related models through the Accretion ORM.

Has One

The has one relationship identifies a single model to load based on the criteria passed.

The has_one method takes up to 4 parameters.

  • $model_name - required
  • $local_field_name - Defaults to the local primary field (i.e. User = user_id)
  • $remote_field_name - Defaults to the local primary field (i.e. User = user_id)
  • $where - Defaults to array(), can be left blank but any orm method can be passed. ex:
    $this->has_one('Account', 'user_id', 'user_id', ['where' => ["user_permission = 'true'"], 'order' => "user_first_name DESC", 'limit' => 6]);
    • In the above example the first has_one parameter is Account which specifies the type of model trying to be loaded.
    • The second has_one parameter is user_id which is the local field we are referencing for the relationship.
    • The third has_one parameter is user_id which says that we want to load the Account model with the same value as the local field value.
    • The fourth value is an array passing multiple query parameters of where statements, how to order the results and how to limit them.



For an example lets look at two models. Below will show a User model and an Account model. We will show how to load the account model from the relationship.


Example:

This is a User Model and would exist in /model/User.php

<?php
	class User extends Model {

		public $structure = array(
			'user_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'user_first_name' 	=> array('Type' => "text",),
			'user_last_name' 	=> array('Type' => "text",),
			'user_email'		=> array('Type' => "varchar(255)",),
			'user_password'		=> array('Type' => "varchar(255)",),
		);

		public function __construct(){
			$this->has_one('Account', 'user_id', 'user_id');
		}
	}

?>
										

Example:

This is an Account Model and would exist in /model/Account.php

<?php
	class Account extends Model {

		public $structure = array(
			'account_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'user_id' 		=> array('Type' => "text",),
			'account_type' 		=> array('Type' => "enum('user','manager','admin')",),
			'account_status'	=> array('Type' => "enum('active','inactive','pending')", 'Default' => "active",),
		);

		public function __construct(){
			$this->has_one('User', 'user_id', 'user_id');
		}
	}

?>
										

Lets assume that the following records exist in the database.


Example:

This is an example record in a table called user in the database.

user_id user_first_name user_last_name user_email user_password
5 John Doe johndoe@gmail.com asdjfgkfsgdfgklhgshdjfkkshdjfgg

Example:

This is an example record in a table called account in the database.

account_id user_id account_type account_status
11 5 admin active

When the User Model is loaded, the Account Model Can be accessed through a simple object oriented command.

$account = \User::find(5)->account();

The above code will load the user record from the database with user_id = '5', load that into the user model, then will find the account record with the corresponding user_id and load a single instance of the Account Model

If no corresponding Account Model was found an empty ORM_Wrapper Object will be returned.


Likewise the following code will load a User Object

$user = \Account::find(11)->user()

And again if not corresponding User Model was found then an empty ORM_Wrapper will be returned.


Has Many

The has many relationship allows you to relate one model to multiple models.

The has many relationship can be called several different ways.

  1. $this->has_many('Target_Model')
  2. $this->has_many('Target_Model', 'local_field_name', 'remote_field_name')
  3. $this->has_many('Target_Model', 'local_field_name', 'remote_field_name', array('where' => "x = y AND a = b", 'order' => "x DESC"))
  4. $this->has_many('Target_Model', array('where' => "x = y AND a = b", 'order' => "x DESC"))

In the #1 example above, the relationship assumes that the Target_Model has a field in the database that matches the current model's primary field.
For example: If we were loading a User model where the primary field was user_id and the Target_Model was Notification, any record in the notification table with the user_id of the current model would be loaded.



For the #1 example above lets assume the following tables/records exist in the database.

Example:

This is an example record in a table called user in the database.

user_id user_first_name user_last_name user_email user_password
5 John Doe johndoe@gmail.com asdjfgkfsgdfgklhgshdjfkkshdjfgg
Example:

This is an example of records in a table called notification in the database.

notification_id user_id notification_title notification_content notification_time
30 8 New Update There is a new update that needs your attention. 2017-11-22 10:22:34
31 5 New Update There is a new update that needs your attention. 2018-05-03 11:23:41
32 5 Password Reset You have requested to reset your password. 2018-06-09 18:06:17
Example:

Now this is an example of the User Model located in /model/User.php

<?php
	class User extends Model {

		public $structure = array(
			'user_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'user_first_name' 	=> array('Type' => "text",),
			'user_last_name' 	=> array('Type' => "text",),
			'user_email'		=> array('Type' => "varchar(255)",),
			'user_password'		=> array('Type' => "varchar(255)",),
		);

		public function __construct(){
			$this->has_many('Notification');
		}
	}

?>
										

Example:

Now this is an example of the Notification Model located in /model/Notification.php

<?php
	class Notification extends Model {

		public $structure = array(
			'notification_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'user_id' 			=> array('Type' => "int(11)",),
			'notification_title' 		=> array('Type' => "varchar(255)",),
			'notification_content'		=> array('Type' => "text",),
			'notification_time'		=> array('Type' => "timestamp", 'Default' => "current_timestamp",),
		);

		public function __construct(){
			$this->has_one('User', 'user_id', 'user_id');
		}
	}

?>
										


Based on the above example models and database records if the following code was ran:

$notifications = \User::find(5)->notification();

The $notifications variable would contain:

ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
            [0] => Notification Object
                (
                    [notification_id] => 31
                    [user_id] => 5
                    [notification_title] => New Update
                    [notification_content] => There is a new update that needs your attention.
                    [notification_time] = 2018-05-03 11:23:41
                )

            [1] => Notification Object
                (
                    [notification_id] => 32
                    [user_id] => 5
                    [notification_title] => Password Reset
                    [notification_content] => You have requested to reset your password.
                    [notification_time] = 2018-06-09 18:06:17
                )
        )

    [_results:ORM_Wrapper:private] => 
)
										


Additionally you can pass parameters when you call the relationship.

$notifications = \User::find(5)->notification(['order' => "notification_id DESC"]);
ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
        	[0] => Notification Object
                (
                    [notification_id] => 32
                    [user_id] => 5
                    [notification_title] => Password Reset
                    [notification_content] => You have requested to reset your password.
                    [notification_time] = 2018-06-09 18:06:17
                )

            [1] => Notification Object
                (
                    [notification_id] => 31
                    [user_id] => 5
                    [notification_title] => New Update
                    [notification_content] => There is a new update that needs your attention.
                    [notification_time] = 2018-05-03 11:23:41
                )            
        )

    [_results:ORM_Wrapper:private] => 
)
											


Here is another example of passing parameters through a relationship.

$notifications = \User::find(5)->notification(['order' => "notification_id DESC", 'where' => "notification_time > '2018-06-01 00:00:00'"]);
ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
        	[0] => Notification Object
                (
                    [notification_id] => 32
                    [user_id] => 5
                    [notification_title] => Password Reset
                    [notification_content] => You have requested to reset your password.
                    [notification_time] = 2018-06-09 18:06:17
                )        
        )

    [_results:ORM_Wrapper:private] => 
)
											

Has One Through

Has One Through leverages an existing relationship and calls the related model's relationship.

Parameters:

  1. model_name - required
  2. map_model - required
  3. map_model_where - default = array()
  4. model_where - default = array()

The #1 parameter is the type of model that you want to load

The #2 parameter is the model that is established already in the calling model

The #3 parameter is a way to filter the interpreting model.

The #4 parameter is a way to filter the final results



Example:
<?php
	class User extends Model {

		public $structure = array(
			'user_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'user_first_name' 	=> array('Type' => "text",),
			'user_last_name' 	=> array('Type' => "text",),
			'user_email'		=> array('Type' => "varchar(255)",),
			'user_password'		=> array('Type' => "varchar(255)",),
		);

		public function __construct(){
			$this->has_many('Notification');
			$this->has_one_through('latest_notification.Notification', 'Notification', ['order' => "notification_time DESC"], []);
		}
	}

?>
										

The above model uses a has_many and a has_one_through method.


If you look at the has_one_through method you will notice the the Notification model is prefixed with latest_notification.

The latest_notification. prefix is an Alias which allows for the same model type to be called in a different way.


First lets look at what just calling ->notification(); would return.

$notifications = \User::find(5)->notification(); would return the following
ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
            [0] => Notification Object
                (
                    [notification_id] => 31
                    [user_id] => 5
                    [notification_title] => New Update
                    [notification_content] => There is a new update that needs your attention.
                    [notification_time] = 2018-05-03 11:23:41
                )

            [1] => Notification Object
                (
                    [notification_id] => 32
                    [user_id] => 5
                    [notification_title] => Password Reset
                    [notification_content] => You have requested to reset your password.
                    [notification_time] = 2018-06-09 18:06:17
                )
        )

    [_results:ORM_Wrapper:private] => 
)
											


However the following example would return a single result of only the latest notification.

$notification = \User::find(5)->latest_notification(); would return the following
Notification Object
    (
        [notification_id] => 32
        [user_id] => 5
        [notification_title] => Password Reset
        [notification_content] => You have requested to reset your password.
        [notification_time] = 2018-06-09 18:06:17
    )
											

So what is happening in the above example is we used the alias latest_notification which was defined as relationship of has_one_through. This means that the user model knows there are multiple Notification models linked to the User model because of the has_many('Notification') method defined in the User Model. Then when the latest_notification method was called, the model checked the relationship and used the order method from the Accretion ORM, found the notifications and filtered down to a single notification based on the criteria in the has_one_through method.

Has Many Through

Has Many Through allows you to identify a set of models that should be loaded based on another model's criteria.

Parameters:

  1. model_name - required
  2. map_model - required
  3. map_model_where - default = array()
  4. model_where - default = array()

The #1 parameter is the type of model that you want to load

The #2 parameter is the model that is established already in the calling model

The #3 parameter is a way to filter the interpreting model.

The #4 parameter is a way to filter the final results



Example:

Lets assume we have the following model for a user.

<?php
	class Contact extends Model {

		public $structure = array(
			'contact_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'contact_first_name' 	=> array('Type' => "text",),
			'contact_last_name' 	=> array('Type' => "text",),
			'contact_email'		=> array('Type' => "varchar(255)",),
			'contact_password'	=> array('Type' => "varchar(255)",),
			'company_id'		=> array('Type' => "int(11)",),
		);

		public function __construct(){
			$this->has_one('Company', 'company_id', 'company_id');
			$this->has_many_through('Contact', 'Company');
		}
	}

?>
										

And lets assume that the company model looks like this.

<?php
	class Company extends Model {

		public $structure = array(
			'company_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'company_name' 	=> array('Type' => "text",),
			'company_address' 	=> array('Type' => "text",),
			'company_status'		=> array('Type' => "enum('active','inactive')", 'Default' => 'active',),
		);

		public function __construct(){
			$this->has_many('Contact', 'company_id', 'company_id');
		}
	}

?>
										

Now because the Contact and Company model relationships are set up correctly we can access all of the contacts at a company directly from the loaded contact.

$contacts = \Contact::find(10)->contact();
ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
            [0] => Contact Object
                (
                    [contact_id] => 10
                    [contact_first_name] => John
                    [contact_last_name] => Doe
                    [contact_email] => asdf@gmail.com
                    [contact_password] = asdfghgh
                    [company_id] = 4
                )

            [1] => Contact Object
                (
                    [contact_id] => 11
                    [contact_first_name] => Jane
                    [contact_last_name] => Doe
                    [contact_email] => asdafdff@gmail.com
                    [contact_password] = asdfasdfghgh
                    [company_id] = 4
                )
        )

    [_results:ORM_Wrapper:private] => 
)
											

Again you can filter reults directly when you call the relationship.

$contacts = \Contact::find(10)->contact(['where' => "contact_id > 10"]);
ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (    
            [0] => Contact Object
                (
                    [contact_id] => 11
                    [contact_first_name] => Jane
                    [contact_last_name] => Doe
                    [contact_email] => asdafdff@gmail.com
                    [contact_password] = asdfasdfghgh
                    [company_id] = 4
                )
        )

    [_results:ORM_Wrapper:private] => 
)
											

You can also limit to a single object instead of a wrapper object.

$contacts = \Contact::find(10)->contact(['where' => "contact_id > 10", 'single' => true]);
Contact Object
    (
        [contact_id] => 11
        [contact_first_name] => Jane
        [contact_last_name] => Doe
        [contact_email] => asdafdff@gmail.com
        [contact_password] = asdfasdfghgh
        [company_id] = 4
    )
											

Aliasing Relationships

Sometimes you may need to create multiple relationships to the same model with different parameters. To accomplish this you should use model aliasing.

Lets assume we have a company that has multiple contacts with different roles.

Example:
<?php
	class Company extends Model {

		public $structure = array(
			'company_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'company_name' 		=> array('Type' => "text",),
			'company_address' 	=> array('Type' => "text",),
			'company_status'	=> array('Type' => "enum('active','inactive')", 'Default' => 'active',),
		);

		public function __construct(){
			$this->has_many('Contact', 'company_id', 'company_id');
			$this->has_many('admin_contacts.Contact', 'Contact', 'company_id', 'company_id', ['where' => "contact_role = 'admin'"]);
			$this->has_many('user_contacts.Contact', 'Contact', 'company_id', 'company_id', ['where' => "contact_role = 'user'"]);
			$this->has_many_through('contact_accounts.Account', 'account.Contact', 'company_id', 'company_id');
			$this->has_many_through('active_user_contacts.Contact', 'user_contacts', [], ['where' => "contact_status = 'active'"]);
		}
	}

?>
										

The above model has 3 references to the contact model (contact,admin_contacts,user_contacts)

When the above company model is loaded all contacts for that company can be loaded by calling ->contact()

When the above company model is loaded all contacts with the admin role can be called by calling ->admin_contacts()

When the above company model is loaded all contacts with the user role can be called by calling ->user_contacts()

When the above company model is loaded the ->contact_accounts() method will call an account model and use the Contact model's aliased relationship named account

When the above company model is loaded the ->active_user_contacts() method will call the users_contacts aliased method then filter it by the contact_status = 'active'

Model Hooks

Model hooks are ways to execute an action when a specific action has been taken on a model.
Model hooks can be turned off by using $this->call_hooks(false). This can be useful if you want to modify a model but not execute the hook(s) that might be called when the model is modified.

Before Create

Before create is called before a new record is added to the database.
Example:

When a new company is created the _before_create_hook method will execute before the data is stored to the database if the method exists.

<?php
	class Company extends Model {

		public $structure = array(
			'company_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'company_name' 		=> array('Type' => "text",),
			'company_address' 	=> array('Type' => "text",),
			'company_status'	=> array('Type' => "enum('active','inactive')", 'Default' => 'active',),
		);

		public function __construct(){
			
		}

		public function _before_create_hook(){
			//execute some code here
			return $this;
		}
	}

?>
										

After Create

After create is called after a new record is added to the database.
Example:

When a new company is created the _after_create_hook method will execute after the data is stored to the database if the method exists.

<?php
	class Company extends Model {

		public $structure = array(
			'company_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'company_name' 		=> array('Type' => "text",),
			'company_address' 	=> array('Type' => "text",),
			'company_status'	=> array('Type' => "enum('active','inactive')", 'Default' => 'active',),
		);

		public function __construct(){
			
		}

		public function _after_create_hook(){
			//execute some code here
			return $this;
		}
	}

?>
										

Before Load

Before load is called before a record is loaded from the database.
Example:

When a company is loaded the _before_load_hook method will execute before the data is loaded from the database if the method exists.

<?php
	class Company extends Model {

		public $structure = array(
			'company_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'company_name' 		=> array('Type' => "text",),
			'company_address' 	=> array('Type' => "text",),
			'company_status'	=> array('Type' => "enum('active','inactive')", 'Default' => 'active',),
		);

		public function __construct(){
			
		}

		public function _before_load_hook(){
			//execute some code here
			return $this;
		}
	}

?>
										

After Load

After load is called after a record is loaded from the database.
Example:

When a company is loaded the _after_load_hook method will execute after the data is loaded from the database if the method exists.

<?php
	class Company extends Model {

		public $structure = array(
			'company_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'company_name' 		=> array('Type' => "text",),
			'company_address' 	=> array('Type' => "text",),
			'company_status'	=> array('Type' => "enum('active','inactive')", 'Default' => 'active',),
		);

		public function __construct(){
			
		}

		public function _after_load_hook(){
			//execute some code here
			return $this;
		}
	}

?>
										

Before Update

Before update is called before an existing record is going to be updated in the database.
Example:

When a company is about to be modified the _before_update_hook method will execute before the model updates the database if the method exists.

<?php
	class Company extends Model {

		public $structure = array(
			'company_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'company_name' 		=> array('Type' => "text",),
			'company_address' 	=> array('Type' => "text",),
			'company_status'	=> array('Type' => "enum('active','inactive')", 'Default' => 'active',),
		);

		public function __construct(){
			
		}

		public function _before_update_hook(){
			//execute some code here
			return $this;
		}
	}

?>
										

After Update

After update is called after an existing record was updated in the database.
Example:

When a company was modified the _after_update_hook method will execute after the model updates the database if the method exists.

<?php
	class Company extends Model {

		public $structure = array(
			'company_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'company_name' 		=> array('Type' => "text",),
			'company_address' 	=> array('Type' => "text",),
			'company_status'	=> array('Type' => "enum('active','inactive')", 'Default' => 'active',),
		);

		public function __construct(){
			
		}

		public function _after_update_hook(){
			//execute some code here
			return $this;
		}
	}

?>
										

Before Delete

Before delete is called before an existing record is about to be deleted from the database.
Example:

When a company is about to be deleted the _before_delete_hook method will execute before the model removes the record from the database if the method exists.

<?php
	class Company extends Model {

		public $structure = array(
			'company_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'company_name' 		=> array('Type' => "text",),
			'company_address' 	=> array('Type' => "text",),
			'company_status'	=> array('Type' => "enum('active','inactive')", 'Default' => 'active',),
		);

		public function __construct(){
			
		}

		public function _before_delete_hook(){
			//execute some code here
			return $this;
		}
	}

?>
										

After Delete

After delete is called after an existing record was deleted from the database.
Example:

When a company was deleted the _after_delete_hook method will execute after the model removes the record from the database if the method exists.

<?php
	class Company extends Model {

		public $structure = array(
			'company_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'company_name' 		=> array('Type' => "text",),
			'company_address' 	=> array('Type' => "text",),
			'company_status'	=> array('Type' => "enum('active','inactive')", 'Default' => 'active',),
		);

		public function __construct(){
			
		}

		public function _after_delete_hook(){
			//execute some code here
			return $this;
		}
	}

?>
										

Schema Builder

The Accretion Schema Builder allows you to define what the database table schema for the related model should be just by modifying the model.
The Accretion Schema Builder only works if it is turned on in the Settings file. (Which it is by default).

Lets assume we have a user model and we want to add a user role field to the database table.

Here is the existing User Model.

Example:
<?php
	class User extends Model {

		public $structure = array(
			'user_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'user_first_name' 	=> array('Type' => "text",),
			'user_last_name' 	=> array('Type' => "text",),
			'user_email'		=> array('Type' => "varchar(255)",),
			'user_password'		=> array('Type' => "varchar(255)",),
		);

		public function __construct(){
			
		}
	}

?>
										


Now lets say that we want to add the field 'user_role' to the 'user' table. We would do it by modifying the $structure variable.

<?php
	class User extends Model {

		public $structure = array(
			'user_id' 		=> array('Type' => "int(11)", 'Extra' => "auto_increment",),
			'user_first_name' 	=> array('Type' => "text",),
			'user_last_name' 	=> array('Type' => "text",),
			'user_email'		=> array('Type' => "varchar(255)",),
			'user_password'		=> array('Type' => "varchar(255)",),
			'user_role'		=> array('Type' => "enum('user','manager','admin')",'Default' => "user",),
		);

		public function __construct(){
			
		}
	}

?>
										


The next time that the user model is loaded it will automatically update the database with the new field.

The schema always follows the format of 'field_name' => array('options')

The options for the schema are 'Type','Default','Null','Extra'

Type should always be the mysql column type ex: (varchar(255))

Default is not required but can be passed to identify what the default value of the field should be.

Null is not required but if it is passed should always be 'Yes' or 'No'

Extra is not required but can take values like "auto_increment" or "current_timestamp"

Helpers

Helpers are classes that can be loaded from anywhere in your application. They are particularly helpful when a controller or a model needs to execute the same code and needs to be called from different locations in the framework.

Creating A Helper

To create a helper add a file with the same name to /helper/Your_Helper.php
Example:
This file would exist in /helper/PDF.php
<?php
	class PDF_Helper extends Helper {

		public function __construct(){
			return $this;
		}

		public function create_pdf($html){
			//do something here to convert html to a pdf
		}
	}
?>
										

The above helper can now be called from anywhere in the application by using \Helper::PDF()->create_pdf($html)


The only caveat is that if you are going to call a helper from within another helper you cannot use \Helper::PDF(); instead you have to use \Helper::get('PDF')->create_pdf($html)

System Helpers

The Accretion Framework deploys with a series of system helpers that are common actions that need to be used in most projects.

Code Release

The code release helper is version control software that helps you manage the files that need to be deployed to a production server or development server (or any server).

By default Accretion deploys with a Builder class located in /controller/Builder.php and is accessable from www.example.com/Builder/code_release

This full blown gui version control software is just like git or any other version control software you may use.

To call this helper simply use \Helper::Code_Release() and the rest is done for you.

CSV

The csv helper allows you to create or read .csv files.

There are two main methods for this helper.

  • to_array($path_to_file); - This will return a parsed array of the csv data.
  • generate($data, $file_name = null); - This will generate a csv file based on an associatave array of data passed to it.


Example:
\Helper::CSV()->to_array('/path/to/csv.csv')

The above will output an associative array representing the csv data.



Example:
\Helper::CSV()->generate($csv_data, 'file_name.csv')

The above will force a download of the csv based on the data passed to it.

Encryption

The encryption helper uses the encryption key that was generated when you installed the Accretion framework and allows you to encrypt or decrypt data.


Example:
\Helper::Encryption()->encrypt('this is some data');
asfdhghjhlkj;lk;afsdfghjafgfghkjlk;kfsgdfghkjlafsgdfghk
											


Example:
\Helper::Encryption()->decrypt('asfdhghjhlkj;lk;afsdfghjafgfghkjlk;kfsgdfghkjlafsgdfghk');
this is some data
											

File

The File Helper helps with file management.

Methods

  1. check_filename($path)
  2. get_files_by_date($directory, $start_date = null, $end_date = null)

The #1 method (check_filename($path)) will create a unique name in the specified directory allowing you to save files without overwriting accidentally.

The #2 method (get_files_by_date()) allows you to pull files from a directory by the date they were created. If you dont pass a start or end date: all files in the specified directory will be returned. If you only provide a start date all files in the specified directory created after the start date will be returned. If you only pass the end date then all files created before the end date in the specified directory will be returned and if you pass both a start or end data then all files in the specified directory that were created between the start and end date will be returned.

File Upload

The File Upload Helper allows you to pass uploaded files and the directory you would like to save them to.
Usage:
\Helper::File_Upload()->directory('/path/to/upload')->files($_FILES);

Parameters

  1. files($files)
  2. directory($directory)
  3. upload()

The #1 method expects the $_FILES array

The #2 method sets the directory that you would like to upload the files to (defaults to /upload/)

The #3 method executes the upload and returns an array of the files uploaded with their original path and their final destination.

Flash

The Flash Helper allows you to store flash messages that can be displayed when a user has taken an action.

Lets say that a user upates their profile. You may want to redirect them somewhere else in the application and have a message display to the user. You would use the flash helper here.

Usage:
\Helper::Flash()->add_flash('message here');


Methods

  1. add_flash($message)
  2. render_flash()



The #1 method allows you to store a flash message to the current session.

The #2 method allows you to render the flash message wherever it is called. After this method is called the flash message is then removed from the current session.



Example:
\Helper::Flash()->add_flash('message here');


Example:
\Helper::Flash()->render_flash();

The above code will render the flash message(s)

Paginate

The Paginate Helper sepperates data into pages and can be called on its own or used through a model.
Usage:
$this->pagination = \Helper::Paginate()->data($data)->limit(10)->generate();


Usage:
$this->pagination = \Contact::find()->paginate(20)->load()


Usage:
$this->pagination = \Company::find()->contact(['paginate' => 20])


To show the page links you would use the below code.

Example:
<?=$this->pagination->render_pagination();?>
Example:
To use the data segment for the current paginated page.
<? foreach($this->pagination->data() as $record): ?>
	do something here
<? endforeach; ?>
											

Process Records

When you have to write a long running script, it can be helpful to see where the script is at in its execution and when it will finish.
Usage:
\Helper::Process_Records()->records($records)->callback(function($key, $record){
	//do some code here
	return 'some message';
})


Redirect

When a you need to redirect a user to a url, you can simplify how redirect them using this helper.
Usage:
\Helper::Redirect()


Methods

  1. flash($message)
  2. to($location)
  3. local($location = null)
  4. app($location = null)
  5. from()

The #1 method sets a flash message

The #2 method redirects the user to any url passed.

The #3 method redirects the user to a location based on what the local url is

The #4 method redirects the user to a location based on the web application path

The #5 method redirects the user to whatever page they came from.

Example:
\Helper::Redirect()->flash("The user was updated")->local('/users');

SFTP

The SFTP Helper allows you to connect to a remote server via ftp.

Validate

The Validate Helper allows you you validate form data.

The Validate Helper is used by setting the initial data to validate, then rendering it to a form, then analyzing it to see if it passes validation rules.

Usage:
$this->validate = \Helper::Validate()


Set

The set method is what sets the data to be validated.

Often your are trying to validate the data from a model. In this case you would use ->expose_data()

Example:
$this->validate->set($data);

Text Field

This will render a text field to the browser.
Example:
$this->validate->text_field('field_name', ['attribute' => ""]);

Email

This will render an email field to the browser.
Example:
$this->validate->email('field_name', ['attribute' => ""]);

Number

This will render a number field to the browser.
Example:
$this->validate->number('field_name', ['attribute' => ""]);

Hidden

This will render a hidden field to the browser.
Example:
$this->validate->hidden('field_name', ['attribute' => ""]);

Textarea

This will render a text area to the browser.
Example:
$this->validate->textarea('field_name', ['attribute' => ""]);

Select

This will render a select field to the browser.
Example:
$this->validate->select('field_name', $options, ['attribute' => ""], $use_key = false);

The $options parameter identifies what the options in the dropdown will be.

Sometimes you may want the value of a dropdown to be different that the what is displayed in the dropdown. For This circumstance you should pass the $options array as an associative array and if you want the key of the array to be the value sent when the form is submitted you shoud use the $use_key = true value

Checkbox

This will render a checkbox to the browser.
Example:
$this->validate->checkbox('field_name', ['attribute' => ""]);

Radio

This will render a radio field to the browser.
Example:
$this->validate->radio('field_name', 'field_value', ['attribute' => ""]);

When using the radio method you should pass what the intended field value is.

Country

This will retrieve an array of all countries.
Example:
$this->validate->select('field_name', $this->validate->country(), ['attribute' => ""]);

State

This will retrieve an array of all states.
Example:
$this->validate->select('field_name', $this->validate->state(), ['attribute' => ""]);

Run

When running validation you can specify the rules for validation.

Example:
$r = array(
	'contact_first_name' 	=> array('reqd' => "The first name is required"),
	'contact_last_name' 	=> array('reqd' => "The last name is required"),
	'contact_email' 	=> array('reqd' => "The email is required", 'email' => "This is not a valid email address")
);
												

Once you have established the rules you can validate.

Example:
if($this->validate->run($_POST, $r)){
	//passed validation
}
else{
	//did not pass validation;
}
												

System Classes

There are several base Accretion Classes designed to help with any application.

Auth

The Auth Class is automatically created and loaded with the current user as long as they are logged in.
Usage:
$this->pagination = \Auth::user()->user_id

Assuming that the user accessing your application is logged in they will be accessable through \Auth::user()



Buffer

Sometimes you may need to render something to the browser but grab the buffer output without disrupting what has already been sent. The buffer helper allows you to unintrusively render files and avoid conflicts.
Example:
$var = 'this is a var';
$res = \Buffer::start(function($var = null){
	echo $var;
}, $var);
										

The output of $res will be 'this is a var'

Config

The Config class allows you to access your applications configuration settings from anywhere in Accretion.
Usage
\Config::get();

Methods

  1. get($parameter = null)

When the get() method is called without passing a setting name the whole configuration object is returned.

When the get() method is called with passing a setting name just that setting is returned.

The configuration options are set in the /system/global/Settings.php file.

For more information about the Settings.php file see Settings

Example:
This is an example of the /system/global/Settings.php file.
<?php		

	//INIT THE CONFIG ARRAY
	$config = array();

	//SET THE DEFAULT CONTROLLER
	$config['default_controller'] = 'Home';

	//GLOBAL ENCRYPTION KEY
	$config['encryption_key'] = "COMPILE_ENCRYPTION_KEY";

	//DEFAULT CSS
	$config['css'] = array(
		'https://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css',
	);

	//DEFAULT JS FILES
	$config['js'] = array(
		'https://code.jquery.com/jquery-1.12.4.js',
		'https://code.jquery.com/ui/1.10.2/jquery-ui.js',
	);

	//SET IP ADDRESSES TO IDENTIFY THE SERVER MODE
	$config['servers'] = array(
		'dev' 	=> 'XXX.XXX.XX.XX',
		'prod' 	=> 'XXX.XXX.XX.XX',
	);

	//DATABASE CREDENTIALS
	$config['database'] = array(
		
		//THE FIRST SET OF CREDENTIALS SHOULD ALWAYS BE THE APPLICATIONS DATABASE
		'main' => array(			

			//IF WE ARE ON THE DEV SERVER
			'dev' => array(
				'host' 		=> 'COMPILE_APP_DEV_DB_HOST',
				'database' 	=> 'COMPILE_APP_DEV_DB_NAME',
				'user'		=> 'COMPILE_APP_DEV_DB_USER',
				'password'	=> 'COMPILE_APP_DEV_DB_PASS'
			),

			//IF WE ARE ON THE PRODUCTION SERVER
			'prod' => array(
				'host' 		=> 'COMPILE_APP_PROD_DB_HOST',
				'database' 	=> 'COMPILE_APP_PROD_DB_NAME',
				'user'		=> 'COMPILE_APP_PROD_DB_USER',
				'password'	=> 'COMPILE_APP_PROD_DB_PASS'
			)
		),
	);
?>
										


\Config::get('servers');
stdClass Object
(
    [dev] => XXX.XXX.XX.XX
    [prod] => XXX.XXX.XX.XX
)
										


\Config::get('servers')->dev;
XXX.XXX.XX.XX


\Config::get();
stdClass Object
(
    [default_controller] => Home
    [encryption_key] => COMPILE_ENCRYPTION_KEY
    [css] => Array
        (
            [0] => https://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css
        )

    [js] => Array
        (
            [0] => https://code.jquery.com/jquery-1.12.4.js
            [1] => https://code.jquery.com/ui/1.10.2/jquery-ui.js
        )

    [servers] => stdClass Object
        (
            [dev] => XXX.XXX.XX.XX
            [prod] => XXX.XXX.XX.XX
        )
    [database] => stdClass Object
        (
            [main] => stdClass Object
                (
                    [host] => COMPILE_APP_DEV_DB_HOST
                    [database] => COMPILE_APP_DEV_DB_NAME
                    [user] => COMPILE_APP_DEV_DB_USER
                    [password] => COMPILE_APP_DEV_DB_PASS
                )

        )

)
										

Database

The DB class lets you directly interact with the database.

Set DB

The set_db() method lets you choose the database that you want to use by its alias name set in /system/global/Settings.php
Example:
\DB::set_db();

The above method will call the default database (main) and use the credentials set in /system/global/Settings.php



Example:
\DB::set_db('permissions');

The above method will call the permissions database and use the credentials set in /system/global/Settings.php

Query

The query() method lets you run a mysql query directly.
Example:
\DB::query("UPDATE users SET user_first_name = 'John' WHERE user_id = '1'");

The above method will run the query passed and update the users table.

Get Row

The get_row() method retrieves a single row from the database as an associative array.
Example:
\DB::get_row("SELECT * FROM user");
array
	(
		[user_id] => 1
		[user_first_name] => John
		[user_last_name] => Doe
		[user_email] => johndoe@gmail.com
	)
											

Get Rows

The get_rows() method retrieves multiple rows from the database as an associative array.
Example:
\DB::get_rows("SELECT * FROM user");
array
	(
		[0] => array
			(
				[user_id] => 1
				[user_first_name] => John
				[user_last_name] => Doe
				[user_email] => johndoe@gmail.com
			)
		[1] => array
			(
				[user_id] => 2
				[user_first_name] => Jane
				[user_last_name] => Doe
				[user_email] => janedoe@gmail.com
			)
	)

											

Insert

The insert method allows you to insert a row into the database and returns the id of the row inserted.
Example:
\DB::insert("user", ['user_first_name' => "Jack", 'user_last_name' => 'Doe', 'user_email' => "jackdoe@gmail.com"]);
3

Update

The update() method allows you to update a row/rows in the database.
Example:
\DB::update("user", ['user_email' => "jacksondoe@gmail.com"], "user_id = 3");
bool(true)

Escape

The escape() method escapes a string for the database.
Example:
\DB::escape("string to escape");
string to escape

ORM Wrapper

The ORM Wrapper class allows you to wrap multiple model classes in a single object and perform various actions on them. By default Accretion will return a wrapper object if the result is more than one model.
The ORM Wrapper class works just like an array in that it allows you to use foreach() to cycle through the models.

Push

The push method allows you to add an object to the orm wrapper.
Example
//LOAD A USER MODEL
$user = \User::find(1);

//INSTANTIATE A NEW WRAPPER OBJECT
$wrapper = new \ORM_Wrapper;

//ADD THE USER MODEL TO THE WRAPPER OBJECT
$wrapper->push($user);

//PRINT THE OBJECT TO THE SCREEN
pr($wrapper);
											

The above will output something like

ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
            [0] => User Object
                (
                    [user_id] => 1
                    [user_fname] => John
                    [user_lname] => Doe
                    [user_email] => johndoe@example.com
                )
        )

    [_results:ORM_Wrapper:private] => 
)
											

Alternatively instead of using push, you can instantiate a wrapper with the data

$wrapper = new \ORM_Wrapper($user);
ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
            [0] => User Object
                (
                    [user_id] => 1
                    [user_fname] => John
                    [user_lname] => Doe
                    [user_email] => johndoe@example.com
                )
        )

    [_results:ORM_Wrapper:private] => 
)
											

Count

The count method allows you to check how many models exist in the wrapper.
Example
//LOAD A USER MODEL
$user = \User::find(1);

//INSTANTIATE A NEW WRAPPER OBJECT
$wrapper = new \ORM_Wrapper;

//ADD THE USER MODEL TO THE WRAPPER OBJECT
$wrapper->push($user);

//PRINT THE OBJECT TO THE SCREEN
pr($wrapper->count());
											

The above will output 1

First

The first method allows you to get the first model in the wrapper.
Example:
$users = \User::find()->load();
ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
            [0] => User Object
                (
                    [user_id] => 1
                    [user_fname] => John
                    [user_lname] => Doe
                    [user_email] => johndoe@example.com
                )
            [1] => User Object
                (
                    [user_id] => 2
                    [user_fname] => Jane
                    [user_lname] => Doe
                    [user_email] => janedoe@example.com
                )
        )

    [_results:ORM_Wrapper:private] => 
)
											

With the above example we can call the first user with the following example.


$users->first();
User Object
(
    [user_id] => 1
    [user_fname] => John
    [user_lname] => Doe
    [user_email] => johndoe@example.com
)
											

Chunk

The chunk method allows you to create chunks of an ORM Wrapper class.
Example:

First lets load some users.

$users = \User::find()->load();
ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
            [0] => User Object
                (
                    [user_id] => 1
                    [user_fname] => John
                    [user_lname] => Doe
                    [user_email] => johndoe@example.com
                )
            [1] => User Object
                (
                    [user_id] => 2
                    [user_fname] => Jane
                    [user_lname] => Doe
                    [user_email] => janedoe@example.com
                )
            [2] => User Object
                (
                    [user_id] => 3
                    [user_fname] => Jack
                    [user_lname] => Doe
                    [user_email] => jackdoe@example.com
                )
            [3] => User Object
                (
                    [user_id] => 4
                    [user_fname] => Joe
                    [user_lname] => Doe
                    [user_email] => joedoe@example.com
                )
        )

    [_results:ORM_Wrapper:private] => 
)
											

Using the above ORM Wrapper class containing 4 users we can chunk them into multiple groups by passing the size of the chunks that we want.


$chunks = $users->chunk(3);
Array
(
	[0] => ORM_Wrapper Object
		(
		    [_position:ORM_Wrapper:private] => 0
		    [_data:ORM_Wrapper:private] => Array
		        (
		            [0] => User Object
		                (
		                    [user_id] => 1
		                    [user_fname] => John
		                    [user_lname] => Doe
		                    [user_email] => johndoe@example.com
		                )
		            [1] => User Object
		                (
		                    [user_id] => 2
		                    [user_fname] => Jane
		                    [user_lname] => Doe
		                    [user_email] => janedoe@example.com
		                )
		            [2] => User Object
		                (
		                    [user_id] => 3
		                    [user_fname] => Jack
		                    [user_lname] => Doe
		                    [user_email] => jackdoe@example.com
		                )
		        )

		    [_results:ORM_Wrapper:private] => 
		)
	[1] => ORM_Wrapper Object
		(
		    [_position:ORM_Wrapper:private] => 0
		    [_data:ORM_Wrapper:private] => Array
		        (
		            [0] => User Object
		                (
		                    [user_id] => 4
		                    [user_fname] => Joe
		                    [user_lname] => Doe
		                    [user_email] => joedoe@example.com
		                )
		        )

		    [_results:ORM_Wrapper:private] => 
		)				
)
											

Set

The set method will update all of the models in the wrapper with the data passed and automatically save them.
Example:

First lets load some users.

$users = \User::find()->load();
ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
            [0] => User Object
                (
                    [user_id] => 1
                    [user_fname] => John
                    [user_lname] => Doe
                    [user_email] => johndoe@example.com
                )
            [1] => User Object
                (
                    [user_id] => 2
                    [user_fname] => Jane
                    [user_lname] => Doe
                    [user_email] => janedoe@example.com
                )
            [2] => User Object
                (
                    [user_id] => 3
                    [user_fname] => Jack
                    [user_lname] => Doe
                    [user_email] => jackdoe@example.com
                )
            [3] => User Object
                (
                    [user_id] => 4
                    [user_fname] => Joe
                    [user_lname] => Doe
                    [user_email] => joedoe@example.com
                )
        )

    [_results:ORM_Wrapper:private] => 
)
											

Now we can update all of the users email addresses and last names by doing the following.


$users->set(['user_email' => 'test@example.com', 'user_lname' => 'Smith']);
ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
            [0] => User Object
                (
                    [user_id] => 1
                    [user_fname] => John
                    [user_lname] => Smith
                    [user_email] => test@example.com
                )
            [1] => User Object
                (
                    [user_id] => 2
                    [user_fname] => Jane
                    [user_lname] => Smith
                    [user_email] => test@example.com
                )
            [2] => User Object
                (
                    [user_id] => 3
                    [user_fname] => Jack
                    [user_lname] => Smith
                    [user_email] => test@example.com
                )
            [3] => User Object
                (
                    [user_id] => 4
                    [user_fname] => Joe
                    [user_lname] => Smith
                    [user_email] => test@example.com
                )
        )

    [_results:ORM_Wrapper:private] => 
)
											

Get Column

The get_column method allows you to get an array of all of the values from the wrapper models.
Example:
$first_names = $users->get_column('user_fname');
Array
	(
		[0] => John
		[1] => Jane
		[2] => Jack
		[3] => Joe
	)
											

To Array

This method will extract the models into an array.
Example:
$users->to_array();
Array
    (
        [0] => User Object
            (
                [user_id] => 1
                [user_fname] => John
                [user_lname] => Smith
                [user_email] => test@example.com
            )
        [1] => User Object
            (
                [user_id] => 2
                [user_fname] => Jane
                [user_lname] => Smith
                [user_email] => test@example.com
            )
        [2] => User Object
            (
                [user_id] => 3
                [user_fname] => Jack
                [user_lname] => Smith
                [user_email] => test@example.com
            )
        [3] => User Object
            (
                [user_id] => 4
                [user_fname] => Joe
                [user_lname] => Smith
                [user_email] => test@example.com
            )
    )
   
											

Filter

The filter method allows you to use any of the ORM Methods to modify the collection of models in the wrapper.

The filter method takes two parameters. $wrapper->filter($where = array(), $new = false);

The were array can contain any of the orm methods.

The new parameter tells the wrapper if you want to modify the existing wrapper or create a new wrapper.


Example:
$users->filter(['where' => "user_id = 3"]);
ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
            
            [0] => User Object
                (
                    [user_id] => 3
                    [user_fname] => Jack
                    [user_lname] => Smith
                    [user_email] => test@example.com
                )
        )

    [_results:ORM_Wrapper:private] => 
)
											

Magic Methods

Any method that a model has access to can be called from the ORM Wrapper class.
Example:

Lets assume the User model has a method called last_email()

$users->last_email();
ORM_Wrapper Object
(
    [_position:ORM_Wrapper:private] => 0
    [_data:ORM_Wrapper:private] => Array
        (
            [0] => User Object
                (
                    [user_id] => 1
                    [user_fname] => John
                    [user_lname] => Smith
                    [user_email] => test@example.com
                )
            [1] => User Object
                (
                    [user_id] => 2
                    [user_fname] => Jane
                    [user_lname] => Smith
                    [user_email] => test@example.com
                )
            [2] => User Object
                (
                    [user_id] => 3
                    [user_fname] => Jack
                    [user_lname] => Smith
                    [user_email] => test@example.com
                )
            [3] => User Object
                (
                    [user_id] => 4
                    [user_fname] => Joe
                    [user_lname] => Smith
                    [user_email] => test@example.com
                )
        )

    [_results:ORM_Wrapper:private] => Array
    	(
    		[0] => johndoe@example.com
    		[1] => janedoe@example.com
    		[2] => jackdoe@example.com
    		[3] => joedoe@example.com
    	)
)						
											

The above method called the last_email() method foreach of the user objects and loaded the return from the method into the _results array.


The results are now accessable using the ->results() method.

$users->results();

Array
	(
		[0] => johndoe@example.com
		[1] => janedoe@example.com
		[2] => jackdoe@example.com
		[3] => joedoe@example.com
	)											

											

Request

The Request class allows you to retrieve various request variables.

Get

The get method will return all of the url parts as well as any Accretion url variables and any get variables.
Example:

This below example will retrieve all parts of the url including Accretion url variables and $_GET variables

The below example assumes the requested url: http://example.com/Dashboard/users/user-info/user_id=5/?extra=this

$vars = \Request::get();
Array
	(
		[0] => Dashbaord
		[1] => users
		[2] => user-info
		[user_id] => 5
		[extra] => this

	)
											

Additionally you can pass a parameter in that you are searching for


$vars = \Request::get(0);
Dashboard
											
$vars = \Request::get('user_id');
5
											
$vars = \Request::get('another');
bool(false)
											

Post

The post method allows you to retrieve and set $_POST data
Example:
\Request::post();
Array
	(
		[0] => first variable
		[1] => second variable
		[2] => third variable
		[named] => fourth variable
	)
											

Just like the get method, you can check for a specific variable


\Request::post(2);
third variable

											

\Request::post('named');
fourth variable

											

\Request::post('extra');
bool(false)

											


Additionally you can set variables.


\Request::post('extra', 'here');
Array
	(
		[0] => first variable
		[1] => second variable
		[2] => third variable
		[named] => fourth variable
		[extra] => here
	)

											

Get Vars

The get_vars() method is just like the get method but doesnt return any url components other than just urls.
Example:

The below example assumes the requested url: http://example.com/Dashboard/users/user-info/user_id=5/?extra=this

$vars = \Request::get_vars();
Array
	(
		[user_id] => 5
		[extra] => this

	)
											
$vars = \Request::get_vars('user_id');
5
											
$vars = \Request::get_vars('another');
bool(false)
											

Empty Post

This method will check if there is nothing in the $_POST array and return true or false.
Example:
\Request::empty_post()
bool(true)
											

Is Ajax

This method will check if this url is being requested by ajax and return true or false.
Example:
\Request::is_ajax()
bool(false)
											

Headers

This method will check for any previously set headers as well as allow you to check for an existing header and set/update a header.
Example:
\Request::headers();
Array
(
    [Host] => example.com
    [Connection] => keep-alive
    [Cache-Control] => max-age=0
    [Upgrade-Insecure-Requests] => 1
    [User-Agent] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36
    [Accept] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
    [Referer] => http://example.com
    [Accept-Encoding] => gzip, deflate
    [Accept-Language] => en-US,en;q=0.8
    [Cookie] => timezone=America/Los_Angeles; PHPSESSID=ba512btpups5k3478m0rtj8kn5
)
											

\Request::headers('host');
example.com
											

\Request::headers('special');
bool(false)
											

\Request::headers('special', 'this is a special header');
Array
(
    [Host] => example.com
    [Connection] => keep-alive
    [Cache-Control] => max-age=0
    [Upgrade-Insecure-Requests] => 1
    [User-Agent] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36
    [Accept] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
    [Referer] => http://example.com
    [Accept-Encoding] => gzip, deflate
    [Accept-Language] => en-US,en;q=0.8
    [Cookie] => timezone=America/Los_Angeles; PHPSESSID=ba512btpups5k3478m0rtj8kn5
    [special] => this is a special header
)
											

Server

This method lets you retrieve the server variables and allows you to search for them and add/update them.
Example:
\Request::server();
Array
(
    [REDIRECT_REDIRECT_UNIQUE_ID] => WXB-4OuUJy6xkc4riKwIrwAAAAA
    [REDIRECT_REDIRECT_STATUS] => 200
    [REDIRECT_UNIQUE_ID] => WXB-4OuUJy6xkc4riKwIrwAAAAA
    [REDIRECT_HANDLER] => application/x-httpd-ea-php54
    [REDIRECT_STATUS] => 200
    [UNIQUE_ID] => WXB-4OuUJy6xkc4riKwIrwAAAAA
    [HTTP_HOST] => example.com
    [HTTP_CONNECTION] => keep-alive
    [HTTP_CACHE_CONTROL] => max-age=0
    [HTTP_UPGRADE_INSECURE_REQUESTS] => 1
    [HTTP_USER_AGENT] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36
    [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
    [HTTP_ACCEPT_ENCODING] => gzip, deflate
    [HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.8
    [HTTP_COOKIE] => timezone=America/Los_Angeles; PHPSESSID=ba512btpups5k3478m0rtj8kn5
    [SERVER_SOFTWARE] => Apache/2.4.27 (cPanel) OpenSSL/1.0.2k mod_bwlimited/1.4
    [SERVER_NAME] => example.com
    [SERVER_ADDR] => 11.11.11.111
    [SERVER_PORT] => 80
    [REMOTE_ADDR] => 00.00.00.00
    [DOCUMENT_ROOT] => /path/to/public_html
    [REQUEST_SCHEME] => http
    [CONTEXT_PREFIX] => /cgi-sys
    [CONTEXT_DOCUMENT_ROOT] => /usr/local/cpanel/cgi-sys/
    [SCRIPT_FILENAME] => /path/to/route.php
)
											
\Request::server('REDIRECT_STATUS');
200
											
\Request::server('new_var');
bool(false)
											
\Request::server('new_var', 'this has been set');
Array
(
    [REDIRECT_REDIRECT_UNIQUE_ID] => WXB-4OuUJy6xkc4riKwIrwAAAAA
    [REDIRECT_REDIRECT_STATUS] => 200
    [REDIRECT_UNIQUE_ID] => WXB-4OuUJy6xkc4riKwIrwAAAAA
    [REDIRECT_HANDLER] => application/x-httpd-ea-php54
    [REDIRECT_STATUS] => 200
    [UNIQUE_ID] => WXB-4OuUJy6xkc4riKwIrwAAAAA
    [HTTP_HOST] => example.com
    [HTTP_CONNECTION] => keep-alive
    [HTTP_CACHE_CONTROL] => max-age=0
    [HTTP_UPGRADE_INSECURE_REQUESTS] => 1
    [HTTP_USER_AGENT] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36
    [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
    [HTTP_ACCEPT_ENCODING] => gzip, deflate
    [HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.8
    [HTTP_COOKIE] => timezone=America/Los_Angeles; PHPSESSID=ba512btpups5k3478m0rtj8kn5
    [SERVER_SOFTWARE] => Apache/2.4.27 (cPanel) OpenSSL/1.0.2k mod_bwlimited/1.4
    [SERVER_NAME] => example.com
    [SERVER_ADDR] => 11.11.11.111
    [SERVER_PORT] => 80
    [REMOTE_ADDR] => 00.00.00.00
    [DOCUMENT_ROOT] => /path/to/public_html
    [REQUEST_SCHEME] => http
    [CONTEXT_PREFIX] => /cgi-sys
    [CONTEXT_DOCUMENT_ROOT] => /usr/local/cpanel/cgi-sys/
    [SCRIPT_FILENAME] => /path/to/route.php
    [new_var] => this has been set
)
											

Stream

This methods allows you to use STDIN Streams to capture data that was sent to your server. (often this is used to consume a curl call)
Example:
\Request::stream();
This is some data that was passed

This is another line of data that was sent to the server