Kohana 3 Controller Constructs - constructor

Trying to use __construct inside a controller to assign some variable but it keeps throwing errors. Hoping that someone can lead me in the right direction.
class Controller_Mobile extends Controller {
public function __construct()
{
parent::__construct();
$iphoneDetect = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$touchDetect = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");
$blackberry = strpos ($_SERVER['HTTP_USER_AGENT'], 'blackberry');
$android = strpos ($_SERVER['HTTP_USER_AGENT'], 'android');
$iphoneDetect = true;
if ($iphoneDetect == true || $touchDetect == true)
{
$directory = "mobile/iphone";
}
else if($android == true)
{
$directory = "mobile/android";
}
}
public function action_index()
{
$this->request->response = 'I am mobile';
}

I actually just found the answer to the question and just thought i would pass it along. In Kohana 3 you use the before() and after() functions.

You have to use both request and response in construct.
public function __construct(Request $request, Response $response)
{
parent::__construct($request,$response);
// your code
}

If you want to use __construct() method, dont forget about Request variable:
public function __construct(Kohana_Request $request)
{
parent::__construct($request);
// your code
}
Thats why you are getting errors with your code.

Related

Pass two variable to method in Laravel

i want to find post by slug also in url ..
but the comments must be found by post_id
Controller
public function post($slug,$id)
{
$post = Post::where('slug',$slug)->first();
$comments = Comment::where('post_id',$id)->get();
return view('content.post',compact('post','comments'));
}
Route
Route::get('post/{slug}', 'PagesController#post')->name('post.show');
Route::get('post/{slug}', 'PagesController#post')->name('post.show');
public function post($slug)
{
$post = Post::where('slug',$slug)->first();
$comments = Comment::where('post_id',$post->id)->get();
return view('content.post',compact('post','comments'));
}
Here you go:
Get post_id from the $post itself.
public function post($slug){
$post = Post::where('slug',$slug)->first();
$comments = Comment::where('post_id',$post->id)->get();
...
}
You can use Route Model Binding to ensure that routes will find your model based on the provided key.
Your Post model will require that you add the following method:
public function getRouteKeyName()
{
return 'slug';
}
Then, in your routes, you can just refer the model directly, and binding will happen automatically:
public function post(App\Post $post)
{
$comments = Comment::where('post_id',$post->id)->get();
return view('content.post',compact('post','comments'));
}
This enables you to to use the following route:
Route::get('post/{post}', 'PagesController#post')->name('post.show');
Now, additionally, to ease up your reference of the comments, add them as relations to your Post model:
public function comments()
{
return $this->hasMany(Comment::class);
}
and your Comment model:
public function post()
{
return $this->belongsTo(Post::class);
}
This will allow you to shorten your controller method even more:
public function post(App\Post $post)
{
return view('content.post',compact('post'));
}
and in your Blade view do the following instead:
#foreach($post->comments as $comment)
From: {{ $comment->name }} blah blha
#endforeach
in web.php:
Route::get('post/{slug}', 'PagesController#post')->name('post.show');
in controller:
public function post($slug)
{
$post = Post::where('slug',$slug)->first();
$comments = Comment::where('post_id',$post->id)->get(); //use founded_post_id to find it's comments
return view('content.post',compact('post','comments'));
}

Conflicting Laravel controllers- one can call method the other gives non-static error

I've taken over the code from another developer, and I'm quite confused and stuck: one controller I can call the class method CLASSS::method perfectly OK. the other Controller has a copy of the orginal code and modified. On the second one, I get the "non-static method" error.
Call Chain:
Controller->Class->filtered results->Controller response
1A) (Working) Conttroller
<?php
namespace App\Http\Controllers\V1;
use App\Site as SiteClass;
use Facades\App\Site;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use App\{
Http\Controllers\Controller,
Http\Requests\SiteRequest,
Helper\ResourceTrait,
Assets,
Alerts,
Licensee,
Permits,
LandOwner,
Utility
};
use Illuminate\Support\Collection;
class SiteController extends Controller
{
private $obj;
public function __construct()
{
$this->obj = new SiteClass();
}
public function index(Request $request)
{
try
{
$data = Site::filter(
($request->has('sort')? $request->input('sort') : ''),
($request->has('filter')? $request->input('filter') : '')
);
...removed some extra code that's not relevant ...
return response($data);
}
catch(\Exception $e)
{
Log::info('Create exception from here?' . $e);
return response(array('error'=>$e->getMessage()),422);
}
} // index
....
}
1B) (Working) Class
<?php
namespace App;
use Illuminate\Support\Facades\Config;
use \App\BaseModel;
class Site extends BaseModel
{
protected $table = 'sites';
protected $fillable = [
"status","structureType","siteId","name","coverage","address","postCode", "subdistrict", "district", "region", "state", "country", "localCouncil", "latitude", "longitude", "dimensions",
"siteHandover", "startBilling", "utilityBillAcct", "utilityBillingAddress", "renewalTerm",
"capex", "opex", "siteManager", "siteManagerPhone", "siteManagerEmail", "siteOwnerManager", "siteOwnerManagerPhone", "siteOwnerManagerEmail"
];
...
// Working Static method call.
public function filter($sort = null, $search = null)
{
$data = $this;
// check if search variable not empty
if ($search != null)
{
$data = $data->where(function ($query) use ($search){
return $query->where($this->table.'.name','like','%'.$search.'%')
->orWhere($this->table.'.status','=',$search)
->orWhere($this->table.'.siteId','like','%'.$search.'%')
->orWhere($this->table.'.address','like','%'.$search.'%')
->orWhere($this->table.'.subdistrict','like','%'.$search.'%')
->orWhere($this->table.'.district','like','%'.$search.'%')
->orWhere($this->table.'.region','like','%'.$search.'%')
->orWhere($this->table.'.state','like','%'.$search.'%')
->orWhere($this->table.'.country','like','%'.$search.'%')
->orWhere($this->table.'.localCouncil','like','%'.$search.'%')
;
});
if ($sort != null)
{
$sorts = explode('|', $sort);
$data = $data->orderBy($sorts[0],$sorts[1]);
}
}
// check if sort variable not empty
if ($sort != null)
{
$sorts = explode('|', $sort);
$data = $data->orderBy($sorts[0],$sorts[1]);
}
else
{
$data = $data->orderBy('siteId','desc');
}
// return data
return $data->paginate(Config::get('api.records'));
}
}
2A) (Failing) Controller
<?php
namespace App\Http\Controllers\V1;
use App\{
Http\Controllers\Controller,
Helper\ResourceTrait,
Http\Requests\OrganisationRequest,
Organisation
};
use Illuminate\{
Http\Request,
Support\Facades\Config,
Support\Facades\Log
};
class OrganisationController extends Controller
{
private $org;
public function __construct()
{
$this->org = new Organisation();
}
public function index(Request $request)
{
try
{
//WORKAROUND: $this->org->... works
$data = Organisation::filter(
($request->has('sort')? $request->input('sort') : ''),
($request->has('filter')? $request->input('filter') : '')
); // FAILS with non-static method call error
return response($data);
}
catch(\Exception $e)
{
return response(array('error'=>$e->getMessage()),422);
}
} // index
}
...
2B) Failing Class
<?php
namespace App;
use Illuminate\Support\Facades\Config;
use \App\BaseModel;
class Organisation extends BaseModel
{
protected $table = 'organisation';
public function filter($sort = null, $search = null)
{
$data = $this;
// check if search variable not empty
if ($search != null)
{
$data = $data->where(function ($query) use ($search){
return $query->where($this->table.'.name','like','%'.$search.'%')
;
});
if ($sort != null)
{
$sorts = explode('|', $sort);
$data = $data->orderBy($sorts[0],$sorts[1]);
}
}
// check if sort variable not empty
if ($sort != null)
{
$sorts = explode('|', $sort);
$data = $data->orderBy($sorts[0],$sorts[1]);
}
else
{
$data = $data->orderBy('name');
}
// return data
return $data->paginate(Config::get('api.records'));
}
}
To my untutored eye, they look identical, yet one works and the other doesn't. Apologies in advance for the volume of code, but I don't know which parts are affecting what. I suspect it's somethng to do with an imported class, but I'm lost frankly :-D
Site has a Facade while Organisation does not.
Facades (from the docs) provide a "static" interface to classes that are available in the application's service container.

Yii2 model save returns true but there is no change in MySQL

Actually, If I update my model in the action of controller(in this case it is actionTest) it gets updated. Here is my code:
public function actionTest()
{
$model = ProviderOrder::find()->where(['is_used' => 0,'type' => Transaction::COD])->orderBy(['id' => SORT_ASC])->one();//const COD = 0
$model->is_used = 1;
$model->save();
}
But in my case I defined afterSave function to my Booking model. There I call getTrackNumber function which has Transaction Class in its body.
class Booking extends ActiveRecord
{
public function afterSave($insert, $changedAttributes)
{
$this->getTrackNumber($this->id);
parent::afterSave($insert, $changedAttributes);
}
public static function getTrackNumber($bookingId){
$transaction = new Transaction();
....
}
}
Inside of Transaction class there is the same code like in actionTest.
But the problem is $model->save() returns true but when I look through phpmyadmin there is no any change is_used is still 0.
But in the first case, i.e. in actionTest everything is fine. Please help me!

Method chainning for join table with pagination on CI 3

I create a core class named MY_Model that extends CI_Model. In this class, I create a method chaining to get all record with pagination like this :
// Take record with paging.
public function get_all_paged()
{
// get argument that passed
$args = func_get_args();
// get_all_paged($offset)
if (count($args) < 2) {
$this->get_real_offset($args[0]);
$this->db->limit($this->_per_page, $this->_offset);
}
// get_all_paged(array('status' => '1'), $offset)
else {
$this->get_real_offset($args[1]);
$this->db->where($args[0])->limit($this->_per_page, $this->_offset);
}
// return all record
return $this->db->get($this->_tabel)->result();
}
So , I just used like this on my controller,
for example
public function index($offset = NULL) {
$karyawan = $this->karyawan->get_all_paged($offset); //get all
}
I am realy confuse to get all record using join, I know join in CI like this :
public function get_all_karyawan() {
$this->db->select('tb_1 , tb_2');
$this->db->from('tb_1');
$this->db->join('tb_2', "where");
$query = $this->db->get();
return $query->result();
}
How to make it into chain in MY_Model?
Any help it so appreciated ...
The good thing in query builder, you can chain your db methods, till get(). So you can define, selects, where queries, limits in different ways.
For example:
public function category($category)
{
$this->db->where('category_id', $category);
return $this;
}
public function get_posts()
{
return $this->db->get('posts')->result();
}
And you can get all posts:
$this->model->get_posts();
Or by category:
$this->model->category(2)->get_posts();
So upon this, in your model:
public function get_all_karyawan() {
$this->db->select('tb_1 , tb_2');
$this->db->join('tb_1', "where");
// Here you make able to chain the method with this
return $this;
}
In your controller:
public function index($offset = NULL) {
$karyawan = $this->karyawan->get_all_karyawan()->get_all_paged($offset);
}

Trying to understand the AsyncToken in Flex/Actionscript

I am trying to understand the way the AsyncToken works in actionscript. How can I call a remote service and ensure that a specific parameter is available in the result or fault event functions? I think it is the async functionality I want to use.
The following code will hopefully explain what I am trying to do. Feel free to modify the code block as your explanation.
Thanks.
public function testSerivceCall(data:Object, callBackCommand:String):void
{
// Assume callBackCommand == "FOO";
// How can I pass in callBackCommand as a parameter to the result or fault events?
// How do I create an async token here?
var remoteObject:RemoteObject;
remoteObject = new RemoteObject();
remoteObject.destination = "zend";
remoteObject.source = "MyService";
remoteObject.endpoint = "http://example.com/service";
remoteObject.test.addEventListener(ResultEvent.RESULT, _handleTestResult);
remoteObject.test.addEventListener(FaultEvent.FAULT, _handleTestFault);
remoteObject.test(data);
}
private function _handleTestResult( event:ResultEvent ) : void
{
// How do I get the async token value?
// How can I get the value of callBackCommand in this code block?
if (callBackCommand == "FOO")
{
// do something related to "FOO"
}
else
{
// do something else with the result event
}
}
private function _handleTestFault( event:FaultEvent ) : void
{
// How do I get the async token value?
// How can I get the value of callBackCommand in this code block?
}
An edit to make this question more clear:
Assume I make the following method call somewhere in my code:
testSerivceCall(personObject, "LoginCommand");
How do I get access to the actual string "LoginCommand" inside the _handleTestResult function block?
The reason I want to do this is because I want to dynamically call back certain functions and hand off the result data to specific commands that I know ahead of time when I am making the service call.
I am just having a time grokking the AsyncToken syntax and functionality.
I did not even need closures. I added a class as below which I called externally.
The call was like this:
public class MyClass
{
...
var adminServerRO:AdminServerRO = new AdminServerRO();
adminServerRO.testSerivceCall("FOO",cptyId);
}
public class AdminServerRO
{
private function extResult( event:ResultEvent, token:Object ) : void
{
//the token is now accessed from the paremeter
var tmp:String = "in here";
}
private function extFault( event:FaultEvent ) : void
{
var tmp:String = "in here";
}
public function testSerivceCall(callBackCommand:String, cptyId:String):void
{
var remoteObject:RemoteObject = new RemoteObject();
remoteObject.destination = "adminServer";
var token:AsyncToken = remoteObject.getCounterpartyLimitMonitorItemNode(cptyId);
token.addResponder(new AsyncResponder(extResult,extFault,cptyId));
}
}
While the accepted answer will accomplish what the original submitter wants it does not actually answer the question which was asked. An AsyncToken is created as a result of a remote method call and is accessible from the ResultEvent. Since AsyncToken is a dynamic class you can add whatever property to it that you want. The code below should demonstrate this:
public function testSerivceCall(data:Object, callBackCommand:String):void
{
var remoteObject:RemoteObject;
remoteObject = new RemoteObject();
remoteObject.destination = "zend";
remoteObject.source = "MyService";
remoteObject.endpoint = "http://example.com/service";
remoteObject.test.addEventListener(ResultEvent.RESULT, _handleTestResult);
remoteObject.test.addEventListener(FaultEvent.FAULT, _handleTestFault);
var token:AsyncToken = remoteObject.test(data);
token.callBackCommand = callBackCommand;
}
private function _handleTestResult( event:ResultEvent ) : void
{
if (event.token.callBackCommand == "FOO")
{
// do something related to "FOO"
}
else
{
// do something else with the result event
}
}
private function _handleTestFault( event:FaultEvent ) : void
{
//event.token.callBackCommand should be populated here too
}
If you want to access the properties used during the remote call (parameters to the call and/or AsycToken), you can make use of closures. Just define the result event handler inside the calling method as a closure. It can then access any variable in the calling function.
public function testSerivceCall(data:Object, callBackCommand:String):void
{
var _handleTestResult:Function = function( event:ResultEvent ) : void
{
// token is visible here now
if (callBackCommand == "FOO")
{
// do something related to "FOO"
}
else
{
// do something else with the result event
}
}
var remoteObject:RemoteObject;
remoteObject = new RemoteObject();
remoteObject.destination = "zend";
remoteObject.source = "MyService";
remoteObject.endpoint = "http://example.com/service";
remoteObject.test.addEventListener(ResultEvent.RESULT, _handleTestResult);
remoteObject.test.addEventListener(FaultEvent.FAULT, _handleTestFault);
var token = remoteObject.test(data);
}
If I'm reading your question correctly, you're trying to figure out how to access the actual data returned by the ResultEvent ?
If so, assuming you've made the call correctly and you've gotten data back in a format you're expecting:
private function _handleTestResult( event:ResultEvent ) : void
{
// you get the result from the result property on the event object
// edit: assuming the class Person exists with a property called name
// which has the value "John"
var person : Person = event.result as Person;
if (person.name == "John")
{
Alert.show("John: " + person.name);
}
else
{
Alert.show("Not John: " + person.name);
}
}
private function _handleTestFault( event:FaultEvent ) : void
{
// Maybe you know the type of the returned fault
var expectedFault : Object = event.fault as MyPredefinedType
if (expectedFault.myPredefinedTypesPredefinedMethod() == "BAR")
{
// something here
}
}
The ResultEvent has a property called result which will hold an instance of the object returned by the result (it might be the output of an XML file if using a web service, or a serialized object if using AMF, for example). This is what you want to access. Similarly, FaultEvent has a fault property that returns the fault information.
Edit: Changed code in _handleTestResult() in response to Gordon Potter's comment.