Get result of function in Laravel and add to another controller - laravel-7

I have this 1st controller.
class ValidatePassController extends Controller
{
protected function doShow(Post $post, Hash $hash)
{
return view('auth.cab.pcab');
}
}
I need to add if view was returned or something like that in the controller below.
class EditController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function xuibomja()
{
if (// in past controller view was returned))
{
return ('stassik');
}
return ('not stassik');
}
}
Any ideas? I have tried to set some vars, but it didn't work, so im out of ideas. Btw can't summary controllers to each other, codes needs to be in different controllers.

It's not the best practice to have a controller to call another controller.
what I recommend you to do is to create a class and move the functionality there, and create a facade to map to this class, and set both controllers to use that common functionality

Related

Codeigniter 4 - call method from another controller

How to call "functionA" from "ClassA" in "functionB" inside "ClassB" ?
class Base extends BaseController
{
public function header()
{
echo view('common/header');
echo view('common/header-nav');
}
}
class Example extends BaseController
{
public function myfunction()
// how to call function header from base class
return view('internet/swiatlowod');
}
}
Well there are many ways to do this...
One such way, might be like...
Assume that example.php is the required Frontend so we will need a route to it.
In app\Config\Routes.php we need the entry
$routes->get('/example', 'Example::index');
This lets us use the URL your-site dot com/example
Now we need to decide how we want to use the functions in Base inside Example. So we could do the following...
<?php namespace App\Controllers;
class Example extends BaseController {
protected $base;
/**
* This is the main entry point for this example.
*/
public function index() {
$this->base = new Base(); // Create an instance
$this->myfunction();
}
public function myfunction() {
echo $this->base->header(); // Output from header
echo view('internet/swiatlowod'); // Output from local view
}
}
When and where you use new Base() is up to you, but you need to use before you need it (obviously).
You could do it in a constructor, you could do it in a parent class and extend it so it is common to a group of controllers.
It's up to you.

Is it possible to do Controller specific routing in MVC5?

I want all my actions in a single controller to point to a specific View folder. I am going to have many AnalyticControllers that Inherit from a parent controller. The goal is to have individual routing for the child controller to the parent controllers view folder.
I have
public class HomeController : Controller
{
//Controller stuff
}
public class HomeAnalyticsController : HomeController
{
//All my actions need to point to /Home/viewInQuestion.cshtml
}
I want all the actions called in the HomeAnalyticsController to point to /Home/(view here)
I would like to avoid pathing all of my returns if possible.
public ActionResult MyAction()
{
return View("../Home/MyAction");
}

Add behavior to existing implementation - C# / Design Pattern

My current implementation for service and business layer is straight forward as below.
public class MyEntity { }
// Business layer
public interface IBusiness { IList<MyEntity> GetEntities(); }
public class MyBusinessOne : IBusiness
{
public IList<MyEntity> GetEntities()
{
return new List<MyEntity>();
}
}
//factory
public static class Factory
{
public static T Create<T>() where T : class
{
return new MyBusinessOne() as T; // returns instance based on T
}
}
//Service layer
public class MyService
{
public IList<MyEntity> GetEntities()
{
return Factory.Create<IBusiness>().GetEntities();
}
}
We needed some changes in current implementation. Reason being data grew over the time and service & client cannot handle the volume of data. we needed to implement pagination to the current service. We also expect some more features (like return fault when data is more that threshold, apply filters etc), so the design needs to be updated.
Following is my new proposal.
public interface IBusiness
{
IList<MyEntity> GetEntities();
}
public interface IBehavior
{
IEnumerable<T> Apply<T>(IEnumerable<T> data);
}
public abstract class MyBusiness
{
protected List<IBehavior> Behaviors = new List<IBehavior>();
public void AddBehavior(IBehavior behavior)
{
Behaviors.Add(behavior);
}
}
public class PaginationBehavior : IBehavior
{
public int PageSize = 10;
public int PageNumber = 2;
public IEnumerable<T> Apply<T>(IEnumerable<T> data)
{
//apply behavior here
return data
.Skip(PageNumber * PageSize)
.Take(PageSize);
}
}
public class MyEntity { }
public class MyBusinessOne : MyBusiness, IBusiness
{
public IList<MyEntity> GetEntities()
{
IEnumerable<MyEntity> result = new List<MyEntity>();
this.Behaviors.ForEach(rs =>
{
result = rs.Apply<MyEntity>(result);
});
return result.ToList();
}
}
public static class Factory
{
public static T Create<T>(List<IBehavior> behaviors) where T : class
{
// returns instance based on T
var instance = new MyBusinessOne();
behaviors.ForEach(rs => instance.AddBehavior(rs));
return instance as T;
}
}
public class MyService
{
public IList<MyEntity> GetEntities(int currentPage)
{
List<IBehavior> behaviors = new List<IBehavior>() {
new PaginationBehavior() { PageNumber = currentPage, }
};
return Factory.Create<IBusiness>(behaviors).GetEntities();
}
}
Experts please suggest me if my implementation is correct or I am over killing it. If it correct what design pattern it is - Decorator or Visitor.
Also my service returns JSON string. How can I use this behavior collections to serialize only selected properties rather than entire entity. List of properties comes from user as request. (Kind of column picker)
Looks like I don't have enough points to comment on your question. So, I am gonna make some assumption as I am not a C# expert.
Assumption 1: Looks like you are getting the data first and then applying the pagination using behavior object. If so, this is a wrong approach. Lets say there are 500 records and you are showing 50 records per fetch. Instead of simply fetching 50 records from DB, you are fetching 500 records for 10 times and on top of it you are adding a costly filter. DB is better equipped to do this job that C# or Java.
I would not consider pagination as a behavior with respect to the service. Its the behavior of the presentation layer. Your service should only worry about 'Data Granularity'. Looks like one of your customer wants all the data in one go and others might want a subset of that data.
Option 1: In DAO layer, have two methods: one for pagination and other for regular fetch. Based on the incoming params decide which method to call.
Option 2: Create two methods at service level. One for a small subset of data and the other for the whole set of data. Since you said JSON, this should be Restful service. Then based on the incoming URL, properly call the correct method. If you use Jersey, this should be easy.
In a service, new behaviors can be added by simply exposing new methods or adding new params to existing methods/functionalities (just make sure those changes are backward compatible). We really don't need Decorator or Visitor pattern. The only concern is no existing user should be affected.

Symfony2, How to secure all controllers in one place using custom function?

I have defined my controller but I would like to secure ALL of them like below :
// In my Controller Class
public function chooseDateAction()
{
if($this->get('MY.roles_features')
->isGranted($this->container->get('request')->get('_route')))
{
// Do something
}
else
{
throw new AccessDeniedException();
}
return array( );
}
I had to design my own 'isGranted' function because roles are dynamic. BTW the function is working properly !
So my question is do I have to repeat the isGranted function in all of my Controllers or I can put it somewhere to reduce the code redundancy.
I know I have to place isGranted in some top level layer of my security, But the question is how and where ?
Try writing a base controller, which will check upon construction, if isGranted method passes, else throws exception. e.g.:
<?php
namespace Acme\DolanBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class BaseController extends Controller
{
public function __construct()
{
if(!$this->get('MY.roles_features')
->isGranted($this->container->get('request')->get('_route')))
{
throw new AccessDeniedException('Gooby pls');
}
}
}
Then just extend the BaseController in your other controllers.

ViewHelper newable/injectable dilemma

I'm trying to design an application following Misko Heverys insights. It's an interesting experiment and a challenge. Currently I'm struggling with my ViewHelper implementation.
The ViewHelper decouples the model from the view. In my implementation it wraps the model and provides the API for the view to use. I'm using PHP, but I hope the implementation is readable for everyone:
class PostViewHelper {
private $postModel;
public function __construct(PostModel $postModel) {
$this->postModel = $postModel;
}
public function title() {
return $this->postModel->getTitle();
}
}
In my template (view) file this could be called like this:
<h1><?php echo $this->post->title(); ?></h1>
So far so good. The problem I have is when I want to attach a filter to the ViewHelpers. I want to have plugins that filter the output of the title() call. The method would become like this:
public function title() {
return $this->filter($this->postModel->getTitle());
}
I need to get observers in there, or an EventHandler, or whatever service (in what I see as a newable, so it needs to be passed in through the stack). How can I do this following the principles of Misko Hevery? I know how I can do this without it. I'm interested in how for I can take it and currently I don't see a solution. ViewHelper could be an injectable too, but then getting the model in there is the problem.
I didn't find the blog post you referenced very interesting or insightful.
What you are describing seems more like a Decorator than anything to do with dependency injection. Dependency injection is how you construct your object graphs, not their state once constructed.
That said, I'd suggest taking your Decorator pattern and running with it.
interface PostInterface
{
public function title();
}
class PostModel implements PostInterface
{
public function title()
{
return $this->title;
}
}
class PostViewHelper implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->post = $post;
}
public function title()
{
return $this->post->title();
}
}
class PostFilter implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->post = $post;
}
public function title()
{
return $this->filter($this->post->title());
}
protected function filter($str)
{
return "FILTERED:$str";
}
}
You'd simply use whatever DI framework you have to build this object graph like so:
$post = new PostFilter(new PostViewHelper($model)));
I often use this approach when building complex nested objects.
One problem you might run into is defining "too many" functions in your PostInterface. It can be a pain to have to implement these in every decorator class. I take advantage of the PHP magic functions to get around this.
interface PostInterface
{
/**
* Minimal interface. This is the accessor
* for the unique ID of this Post.
*/
public function getId();
}
class SomeDecoratedPost implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->_post = $post;
}
public function getId()
{
return $this->_post->getId();
}
/**
* The following magic functions proxy all
* calls back to the decorated Post
*/
public function __call($name, $arguments)
{
return call_user_func_array(array($this->_post, $name), $arguments);
}
public function __get($name)
{
return $this->_post->get($name);
}
public function __set($name, $value)
{
$this->_post->__set($name, $value);
}
public function __isset($name)
{
return $this->_post->__isset($name);
}
public function __unset($name)
{
$this->_post->__unset($name);
}
}
With this type of decorator in use, I can selectively override whatever method I need to provide the decorated functionality. Anything I don't override is passed back to the underlying object. Multiple decorations can occur all while maintaining the interface of the underlying object.

Resources