Computation Inside Model Codeigniter - codeigniter

Good day everyone. I just wanna know if it's possible to do computations inside a model, disregarding the database? If it is, how will I do it? If not, can someone explain? Thanks.
Example:
var $monthly = '';
var $annually = '';
var $quarterly = '';
var $semiannual = '';
function computation($price, $quantity){
$this->monthly = $price * $quantity;
$this->annually = $price * $quantity * 12;
$this->quarterly = $price * $quantity * 3;
$this->semiannual = $price * $quantity * 6;
}

Models are just regular classes - you write methods to do your calculation and then call them from the controllers as needed. See example below:
class Circle extends CI_Model {
public function area($rad) {
return 3.14 * $rad * $rad;
}
}
class CircleCtrl extends CI_Controller {
public function calc_area() {
$this->load->model('Circle');
$area = $this->circle->area(10);
}
}

Related

Get formatted values from custom Form Request - Laravel 5.6

I`m using custom form request to validate all input data to store users.
I need validate the input before send to form request, and get all validated data in my controller.
I have a regex function ready to validate this input, removing unwanted characters, spaces, allow only numbers and etc.
Would to get all data validated in controller, but still have no success.
Input example:
$cnpj= 29.258.602/0001-25
How i need in controller:
$cnpj= 29258602000125
UsuarioController
class UsuarioController extends BaseController
{
public function cadastrarUsuarioExterno(UsuarioStoreFormRequest $request)
{
//Would to get all input validated - no spaces, no!##$%^&*, etc
$validated = $request->validated();
dd($data);
}
...
}
UsuarioStoreFormRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;
class UsuarioStoreFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'cnpj' => 'required|numeric|digits:14',
];
}
Custom function to validate cnpj
function validar_cnpj($cnpj)
{
$cnpj = preg_replace('/[^0-9]/', '', (string) $cnpj);
// Valida tamanho
if (strlen($cnpj) != 14)
return false;
// Valida primeiro dígito verificador
for ($i = 0, $j = 5, $soma = 0; $i < 12; $i++)
{
$soma += $cnpj{$i} * $j;
$j = ($j == 2) ? 9 : $j - 1;
}
$resto = $soma % 11;
if ($cnpj{12} != ($resto < 2 ? 0 : 11 - $resto))
return false;
// Valida segundo dígito verificador
for ($i = 0, $j = 6, $soma = 0; $i < 13; $i++)
{
$soma += $cnpj{$i} * $j;
$j = ($j == 2) ? 9 : $j - 1;
}
$resto = $soma % 11;
return $cnpj{13} == ($resto < 2 ? 0 : 11 - $resto);
}
You could use the prepareForValidation method in your FormRequest. This way your input would be modified and replaced in the request before it is validated and you can normally retrieve it in the controller with $request->get('cnpj'); after the validation was successful.
public function prepareForValidation()
{
$input = $this->all();
if ($this->has('cnpj')) {
$input['cnpj'] = $this->get('cnpj'); // Modify input here
}
$this->replace($input);
}
You could extend the validated function in UsuarioStoreFormRequest as follows
/**
* Get the validated data from the request.
*
* #return array
*/
public function validated()
{
$validated = parent::validated();
//Add here more characters to remove or use a regex
$validated['cnpj'] = str_replace(['-', '/', ' ', '.'], '', $validated['cnpj']);
return $validated;
}
Do it like this:
$string = "29.258.602/0001-25";
preg_match_all('!\d+!', $string, $matches);
return (implode("",$matches[0]));
Hope its help

Send Data From Controller to View Code Igniter

I have an function get() on my controller. This function I use to get data from database and I save it to $data variable.
It's possible to call get() function on another function and I send the $data variable to the view? I want to make two view, one is classic and another one is modern view.
This is my code:
public function get()
{
$data['all'] = $this->genbamodel->getAll();
$data['delay'] = $this->genbamodel->getDelay();
$data['ontime'] = $this->genbamodel->getOntime();
$data['ahead'] = $this->genbamodel->getAhead();
$data['unloading'] = $this->genbamodel->getUnloading();
$data['topdelay'] = $this->genbamodel->getTopDelay();
$data['topahead'] = $this->genbamodel->getTopAhead();
$data['jumlah'] = count($this->genbamodel->getID())+1;
for ($j=1; $j < $data['jumlah']; $j++) {
$datas['lalax'.$j] = $this->genbamodel->getRecord($j);
$data['lala'.$j] = array_reverse($datas['lalax'.$j]);
}
$data['time'] = $this->genbamodel->getTime();
}
public function home_classic()
{
$this->get();
$this->load->view('home_classic',$data);
}
public function home_modern()
{
$this->get();
$this->load->view('home_modern',$data);
}
Hope this will help you :
Your get() method should return $data
public function get()
{
$data['all'] = $this->genbamodel->getAll();
$data['delay'] = $this->genbamodel->getDelay();
$data['ontime'] = $this->genbamodel->getOntime();
$data['ahead'] = $this->genbamodel->getAhead();
$data['unloading'] = $this->genbamodel->getUnloading();
$data['topdelay'] = $this->genbamodel->getTopDelay();
$data['topahead'] = $this->genbamodel->getTopAhead();
$data['jumlah'] = count($this->genbamodel->getID())+1;
for ($j=1; $j < $data['jumlah']; $j++) {
$datas['lalax'.$j] = $this->genbamodel->getRecord($j);
$data['lala'.$j] = array_reverse($datas['lalax'.$j]);
}
$data['time'] = $this->genbamodel->getTime();
return $data;
}
in home_classic() do it like this
public function home_classic()
{
$data = $this->get();
$this->load->view('home_classic',$data);
}
in home_modern() do the same
public function home_modern()
{
$data = $this->get();
$this->load->view('home_modern',$data);
}
for more : https://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view

why we use $this__("Some text") instead simple echo magento

I am working with magento and have a question in mind that why we use $this__("Some text") instead simple echo magento. can anyone ?
When you call
echo $this->__("some text");
You can start by looking at Mage_Core_Helper_Abstract
/**
* Translate
*
* #return string
*/
public function __()
{
$args = func_get_args();
$expr = new Mage_Core_Model_Translate_Expr(array_shift($args), $this->_getModuleName());
array_unshift($args, $expr);
return Mage::app()->getTranslator()->translate($args);
}
Next is Mage_Core_Model_App
/**
* Retrieve translate object
*
* #return Mage_Core_Model_Translate
*/
public function getTranslator()
{
if (!$this->_translator) {
$this->_translator = Mage::getSingleton('core/translate');
}
return $this->_translator;
}
Which is handed to Mage_Core_Model_Translate
/**
* Translate
*
* #param array $args
* #return string
*/
public function translate($args)
{
$text = array_shift($args);
if (is_string($text) && ''==$text
|| is_null($text)
|| is_bool($text) && false===$text
|| is_object($text) && ''==$text->getText()) {
return '';
}
if ($text instanceof Mage_Core_Model_Translate_Expr) {
$code = $text->getCode(self::SCOPE_SEPARATOR);
$module = $text->getModule();
$text = $text->getText();
$translated = $this->_getTranslatedString($text, $code);
}
else {
if (!empty($_REQUEST['theme'])) {
$module = 'frontend/default/'.$_REQUEST['theme'];
} else {
$module = 'frontend/default/default';
}
$code = $module.self::SCOPE_SEPARATOR.$text;
$translated = $this->_getTranslatedString($text, $code);
}
//array_unshift($args, $translated);
//$result = #call_user_func_array('sprintf', $args);
$result = #vsprintf($translated, $args);
if ($result === false) {
$result = $translated;
}
if ($this->_translateInline && $this->getTranslateInline()) {
if (strpos($result, '{{{')===false || strpos($result, '}}}')===false || strpos($result, '}}{{')===false) {
$result = '{{{'.$result.'}}{{'.$translated.'}}{{'.$text.'}}{{'.$module.'}}}';
}
}
return $result;
}
which returns the resulting text. This is a quick walkthrough of how everything would be handled, you should view the classes themselves to get a more in-depth understanding.
In simple when you call echo $this->__('some text') it look up same
text in CSV file which is located in
app>locale
or
app>design>frontend>YOUR_PACKAGE>YOUR_THEME_NAME>locale>translate.csv
file if the same word exist then it translate a word
means it is very useful in multi-language website
$this->__("Some text")
Used for translation purpose

Codeigniter: How to declare a global variable for a recursive function, and how to return it?

I want to use recursion in a model in Codeigniter, and am baffled as to where I should declare the global variable to be used in the recursive function.
I'm trying to show a catalog of products, ordered by their geographical classification. The recursion is needed because the geographical database is a hierarchy tree, where a place can have sons, grandsons, great-grandsons etc (for example: London is the son of England, which is the son of Britain, which is the son of Europe).
At the end of the recursion, I want to return the variable $arrCatalog, which will hold all the products. So my other question is how to return that variable in the end?
Here is my code (not tested yet, because I didn't know how to handle the global variable):
class Catalogs_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
function getCatalog($place_id, $prod_type)
{
$sql =
"SELECT id, heb_name, type FROM places p
INNER JOIN places_relations r ON p.id = r.son
WHERE father = ?
ORDER BY sort_name";
$query = $this->db->query($sql, $place_id);
if($query->num_rows() > 0) {
foreach ($query->result() as $place) {
$sql2 =
"SELECT code, heb_title, price, place_id FROM products
INNER JOIN products_places ON prod_code=code
WHERE place_id = ? AND prod_type = ?";
$query2 = $this->db->query($sql, $place_id, $prod_type);
if($query2->num_rows() > 0) {
foreach ($query2->result() as $product) {
$arrCatalog[] = $product; // $arrCatalog is the global variable I don't know where to declare and how to return.
}
$this->getCatalog($place['id'], $prod_type);
}
}
}
}
}
Pass your variable to the current object ($this), then you can pass it around your model or hand it to a controller.
class Catalogs_model extends CI_Model {
public $arrCatalog = array();
public function __construct() {
parent::__construct();
}
function getCatalog($place_id, $prod_type) {
$sql = "SELECT ...";
$query = $this->db->query($sql, $place_id);
if($query->num_rows() > 0) {
foreach ($query->result() as $place) {
$sql2 = "...";
$query2 = $this->db->query($sql, $place_id, $prod_type);
if($query2->num_rows() > 0) {
foreach ($query2->result() as $product) {
$this->arrCatalog[] = $product;
}
$this->getCatalog($place['id'], $prod_type);
}
}
}
}
Your controller:
$this->catalogs_model->getCatalog(2, 'hebBook');
$data['data_rows'] = $this->catalogs_model->arrCatalog;
Testing, alter your model like so ....
class Catalogs_model extends CI_Model {
public $arrCatalog = array();
// add these variables for testing ....
private $greeting = 'Hello'; // notice this is private? You cannot access this from your controller but you can from anywhere within the Catalogs_model class.
public $output = ''; // public
public $string = null; // public
// your existing code ...
function hello ()
{
$this->output = $this->greeting;
}
function hello_string ()
{
if($this->string)
{
$this->output = $this->greeting.' '.$string;
}
}
} // end class
Now test in your controller
$this->catalogs_model->hello(); // runs the hello function which sets the model->output
echo $this->catalogs_model->output; // echos 'Hello'
echo '<br />'; // just so the output stands apart in your browser.
$this->catalogs_model->string = 'World!';
$this->catalogs_model->hello_string();
echo $this->catalogs_model->output; // echos Hello World!

Get nearby locations using google places api in php/codeigniter

I have to fetch results of nearby locations within 2 km of my given latitude/longitude values. Have to do it using Google Places API. Details go here:
http://code.google.com/apis/maps/documentation/javascript/places.html
They have provided a sample code in javascript. But I need to have this in php. Can anyone give me any idea how may I achieve it? Or how may I use this same javascript code in my php controller class? [I am using code igniter framework]. I have been stuck on this issue for so many hours. It will be great if someone can provide a sample php code. Highly appreciate any assistance.
Here is the code of my controller class:
<?php
class Welcome extends CI_Controller {
public function index()
{
$config = "";
//$this->load->library('googlemaps');
$this->load->library('googlemaps');
$config['center'] = '37.4419, -122.1419';
$config['zoom'] = 'auto';
$config['places'] = TRUE;
$config['placesLocation'] = '37.4419, -122.1419';
$config['placesRadius'] = 200;
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
$this->load->view('map_view', $data);
}
}
?>
This is the error I encounter while I try to run the above code:
Fatal error: Using $this when not in object context in /Applications/XAMPP/xamppfiles/htdocs/ciplaces/application/controllers/mapcontroller.php on line 9
I am accessing my code using this url:
http://localhost/ciplaces/index.php/mapcontroller
Thanks
I've got a CodeIgniter library that has integration with the Google Maps and Places API. You can find information and download the library here:
http://biostall.com/codeigniter-google-maps-v3-api-library
A demo of the 'Places' integration can also be found below:
http://biostall.com/demos/google-maps-v3-api-codeigniter-library/places
Give me a shout if you have any questions or require any changes made to the library and I'll be happy to help out where I can.
Cheers
I have done something simular in PHP using the Lumb algorithm.
You should be able to get something from the code below (sits in my model, but you can put in anywhere).
public function search($start_latitude, $start_longitude, $radius, $radius_type, $offset, $limit)
{
$results = array();
$locations = array();
$sql = "SELECT `location_id`, `latitude`, `longitude` FROM `table`";
$query = $this->db->query($sql);
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$geo_data = $this->_bearing_distance_calc($start_latitude, $start_longitude, $row->latitude, $row->longitude, $radius_type);
$geo_data['radius_type'] = $radius_type;
if($geo_data['distance'] <= $radius)
{
// radial serach results
$locations[] = $row->location_id;
}
}
// return amount requested
$results['total'] = count($locations);
$results['locations'] = array_slice($locations, $offset, $limit);
return $results;
}
else
{
// no results
return FALSE;
}
}
/**
* Calculate Distance Between two points.
*
* This method is used to calculate the distance between to geographical points. <br />
* Used by the search method.
*
* #access private
*
* #param float $device_latitude
* #param float $device_longitude
* #param float $beach_latitude
* #param float $beach_longitude
* #param integer $radius_type
*
* #return array
*/
private function _bearing_distance_calc($start_latitude, $start_longitude, $building_latitude, $building_longitude, $radius_type)
{
// using Rhumb lines(or loxodrome)
// convert to rads for php trig functions
$start_latitude = deg2rad($start_latitude);
$start_longitude = deg2rad($start_longitude);
$building_latitude = deg2rad($building_latitude);
$building_longitude = deg2rad($building_longitude);
// testing variables
//$start_latitude = deg2rad(39.4422);
//$start_longitude = deg2rad(-122.0307);
//$building_latitude = deg2rad(49.4422);
//$building_longitude = deg2rad(-112.0307);
// calculate delta of lat and long
$delta_latitude = $building_latitude-$start_latitude;
$delta_longitude = $building_longitude-$start_longitude;
// earth radius
if ($radius_type == 'miles') // using miles
{
$earth_radius = 3959;
}
else // using kilometers
{
$earth_radius = 6371;
}
// now lets start mathing !!
// cast types
$dPhi = log(tan($building_latitude/2+M_PI/4)/tan($start_latitude/2+M_PI/4));
if ($dPhi != 0)
{
$q = $delta_latitude/$dPhi;
}
else
{
$q = cos($start_latitude);
}
//$q = (!is_nan($delta_latitude/$dPhi)) ? $delta_latitude/$dPhi : cos($start_latitude); // E-W line gives dPhi=0
// if dLon over 180° take shorter rhumb across 180° meridian:
if (abs($delta_longitude) > M_PI)
{
$delta_longitude = $delta_longitude>0 ? -(2*M_PI-$delta_longitude) : (2*M_PI+$delta_longitude);
}
$geo_data = array();
$geo_data['distance'] = sqrt($delta_latitude*$delta_latitude + $q*$q*$delta_longitude*$delta_longitude) * $earth_radius;
$bearing = rad2deg(atan2($delta_longitude, $dPhi));
if($bearing < 0)
{
$bearing = 360 + $bearing;
}
$geo_data['bearing'] = $bearing;
return $geo_data;
}

Resources