Access $this->params and $this->data in components.
class LoginComponent extends Object {
/* */
public function login() {
pr($this->params);
pr($this->data);
}
}
I am using this in cake v1.2. I would like to know solution of this in v1.2 as well as v2.1. Please give me a suggestion.
Have a look at some components in your lib. I know this for Cake 2.x, not for 1.2.x. update: as mark mentioned in the comments, this works the same for the 1.x versions.
For example, when I open the SecurityComponent I will find a function called startup(). This method defines itself as:
public function startup(Controller $controller) {
//Rest of code goes here
}
as you can see, they import the Controller object. What you could right now is access the Controlelr methods and variables. Because as you might know: the $this when calling $this->data refers to the Controller.
So, if I store this $controller in a protected variable called $_Controller in my component, I can easily access the data and params like so:
# CakePhp 2.x
$this->_Controller->request->data;
$this->_Controller->request->params;
# CakePhp 1.x
$this->_Controller->data;
$this->_Controller->params;
Have a look at this answer as well.
Check by Router:
Router::getParams();
Related
I have an api and some routes are public some need to be protected via auth. I want to have them in one controller class as they are related. I can extend the controller and have beforeRoute function but it runs for any route that is in that controller. is it possible to add a middleware only to specific routes? I'm a js dev and in express I can just pass middleware functions for any route, even multiple middlewares.
class Clanky /*extends \controllers\ProtectedController */{
public function post_novy_clanek(\Base $base) {
//needs to be protected
}
public function get_clanky(\Base $base) {
}
public function get_clanek(\base $base) {
}
public function get_kategorie(\Base $base) {
}
}
PHP is new to me, I just want to know how I can implement the concepts I know from other languages and frameworks in this weird fatfree framework. Thanks.
Use can use f3-access plugin for that purpose https://github.com/xfra35/f3-access
Fatfree is not opinionated about how to do this.. other options to solve this ask might be:
Use php8 attributes on the method and check these in beforeroute.
Consider an own named route naming schema like #admin_routename and apply checking auth in beforeroute
Use f3-middleware plugin and add auth there
Extend an other admin controller that provides auth in beforeroute or use a trait.
I have a Controller class that extends from AppController in CakePHP.
And this Controller class has a public function .. lets say testFunc()
class xyzController extends AppController {
..
..
public function testFunc($params, $auth_username)
{
..
..
}
}
I have made this function public since I need to call it from another Controller that too extending from AppController.
class abcController extends AppController {
..
..
public function callingFunc()
{
...
$controller = new xyzController($this->request, $this->response);
$controller->testFunc($params, $username);
}
..
..
}
But since I made it public, I see that testFunc() is accessible using curl command for the below https path
https://[ip_address]/xyz/testFunc/arg=test/root
As you can see, the above path takes "root" as argument to testFunc() and gives full access to anyone using the above path in curl command.
My requirement is to remove this security issue.
I am totally new to PHP and CakePHP. Can someone please give any pointers to how I can proceed?
"I need to call it from another Controller". This is almost never actually true, it usually indicates a flawed design. If testFunc is not meant to be accessed through a browser, then move it to somewhere that both controllers can access it without it being a public member. For example, make it a protected (or even private) member of your AppController, or if it's doing model-specific stuff, maybe it can be moved to that model's table class.
The solution is pretty simple.
public function _testFunc($params, $auth_usernmae) will do the magic.
In Cakephp, if the function has an underscore as prefix, then it cannot be accessed using URI but can be accessed internally from other functions.
I have been declaring all the routes for my application inside web.php , but it is now getting quite large. I find that I am losing a lot of time shifting between web.php and each controller and this is hurting productivity.
I feel like it would be better to define routes inside of the controller, perhaps ideally delegating some URL to a controller and then allowing the controller to handle the "sub routes" since this would allow me to use inheritance when I have two similar controllers with similar routes.
It is not possible given how laravel works. Every request is passed onto router to find its designated spot viz. the controller with the method. If it fails to find the route within the router, it just throws the exception. So the request never reaches any controller if the route is not found. It was possible in earlier versions on Symphony where you would configure the route in the comment of a particular controller method.
Sadly with laravel it works how it works.
But for me, I just like to have the routes in a separate file.
Alternate solution, easier way to sort all the routes.
You can move your route registration into controllers if you use static methods for this. The code below is checked in Laravel 7
In web.php
use App\Http\Controllers\MyController;
.....
MyController::registerRoutes('myprefix');
In MyController.php
(I use here additional static methods from the ancestor controller also posted below)
use Illuminate\Support\Facades\Route;
.....
class MyController extends Controller {
......
static public function registerRoutes($prefix)
{
Route::group(['prefix' => $prefix], function () {
Route::any("/foo/{$id}", self::selfRouteName("fooAction"));
Route::resource($prefix, self::selfQualifiedPath());
}
public function fooAction($id)
{
........
}
In Controller.php
class Controller extends BaseController {
....
protected static function selfAction($actionName, $parameters = [], $absolute = false)
{
return action([static::class, $actionName], $parameters, $absolute);
}
protected static function selfQualifiedPath()
{
return "\\".static::class;
}
protected static function selfRouteName($actionName)
{
//classic string syntax return "\\".static::class."#".$actionName;
// using tuple syntax for clarity
return [static::class, $actionName];
}
}
selfAction mentioned here is not related to your question, but mentioned just because it allows making correct urls for actions either by controller itself or any class using it. This approach helps making action-related activity closer to the controller and avoiding manual url-making. I even prefer making specific functions per action, so for example for fooAction
static public function fooActionUrl($id)
{
return self::selfAction('foo', ['id' => $id]);
}
Passing prefix into registerRoutes makes controller even portable in a sense, so allows inserting it into another site with a different prefix in case of conflict
I have a laravel app and have created a SocialMediaController to get the latest posts from twitter and instagram and store them in the database.
I need them to be universally accessible and know I can access it via the IOC.
public function doSomething(App\Http\Controllers\SocialMediaController
$SocialMedia) {
}
However if feels wrong to inject a controller like this. What is be best way to wrap up these methods for global use?
It seems like you want to share some logic you have in the SocialMediaController with another controller, right?
Instead of trying to pass a controller instance to the controller action using the service container, you may move the current logic to a service. Refer to Service Container and Service Providers in the Laravel docs on how to create your own services.
Another way to achieve that is using a trait. Check this answer on how you can do that https://stackoverflow.com/a/30365349/1128918. You would end up with something like this:
trait SocialFeeder {
public function getLatestFromTwitter() {
...
}
}
And, then, you can use that new trait with your controllers:
class SocialMediaController extends Controller {
use SocialFeeder;
public function doSomething() {
...
$tweets = $this->getLatestFromTwitter();
...
}
}
I read in the documentation how to use a controller as a service. But I am not sure what would be the purpose of it. Why not then simply use a service (a class define as a service)?
If anyone could give me some good examples of transforming a controller in a service that would be great.
The classical Symfony controller uses a Service Locater pattern to pull in it's dependencies:
class PersonController
{
public function showAction()
{
$personRepository =
$this->getDoctrine()->getEntityManager()->getRepository('Entity\Person');
$person = $personRepository->find(1);
return new JsonResponse($person);
Getting the person repository requires the action to have quite a bit of knowledge about how to locate things. Somewhat magical in fact . The controller is tied directly to doctrine and the framework infrastructure.
It also makes the action hard to test. You have to make a container then define the necessary services before running the action.
Contrast that with a controller defined as a service with it's dependencies injected:
class PersonController
{
protected $personRepository;
public function __construct($personRepository)
{
$this->personRepository = $personRepository;
}
public function showAction()
{
$person = $this->personRepository->find(1);
The action no longer needs know about how to locate the repository. It's just there. For testing, just need to make a repository and inject it. Clean and simple.