How can i get current module name [nwidart/laravel-modules] - laravel

How can i get current module name, or current namespace. of laravel
I use this library [nwidart/laravel-modules].
I trid this code but not solve problem
$module_name = basename(__FILE__, '.module');

To get module entity: $module = Module::find('blog');
To get module name: $module->getName();
This is documented pretty well by package author here:
https://nwidart.com/laravel-modules/v1/advanced-tools/module-methods

Add this to your modules __construct controller :
private $module_name;
public function __construct()
{
$class = get_called_class(); // or $class = static::class;
$arr_class = explode("\\", $class);
$this->module_name = $arr_class[1];
}
public function index()
{
echo $this->module_name;
}

Related

How to get Class Method on Laravel

Hello I try to get all Methods on a Class Controller on Laravel but I was failed.
I use get_class_methods function to get class methods.
Here is my ConfigController codes:
use Modules\Order\Http\Controllers\V1\Web\OrderController;
class ConfigController extends Controller
{
public function index(){
$methods = get_class_methods(new OrderController::class);
dd($methods);
}
}
After executing the code the result is:
Class "Modules\Order\Http\Controllers\V1\Web\OrderController" not found
And I'm sure that that class exists on that namespace because I have already called it on route.
How to do that on the right way?
Thank you.
Have you tried reflection yet? My example below:
$reflection = new ReflectionMethod($className, $methodName);
$parameter = $reflection->getParameters();
foreach ($parameter as $param) {
echo $parameter->getName();
echo $parameter->isOptional();
}
This is the answer, I just miss s on the method name:
use ReflectionClass;
...
$reflection = new ReflectionClass(OrdersController);
dd($reflection);
...

Loading view inside a Library, issues with cached vars

I am trying to implement a widgets library using load->view. I know I can use include to call directly the file and avoid the vars cache issues but just wondering why it does not work.
Here is how I have structured my code:
My Controller:
class Page extends MY_Controller {
public $data = array();
public function __construct() {
parent::__construct();
...
$this->load->library('widgetmanager');
}
public function index($slug = '') {
echo $this->widgetmanager->show(2);
echo $this->widgetmanager->show(1);
}
}
My Library
class WidgetManager
{
private $CI;
public function __construct()
{
$this->CI = & get_instance();
}
public function show($widget_id) {
$data = array();
$widget_id = (int)$widget_id;
$this->CI->db->select('*');
$this->CI->db->from('widget');
$this->CI->db->where('id', $widget_id);
$query = $this->CI->db->get();
$item = $query->row_array();
$data['widget_title'] = $item['title'];
$data['widget_content'] = $item['content'];
$widget = $this->CI->load->view('widget/'.$item['source'], $data, TRUE);
$data['widget_title'] = '';
$data['widget_content'] = '';
$this->CI->load->view('widget/'.$item['source'], $data);
return $widget;
}
}
widget 1: Calls widget/content
widget 2: Calls widget/banner
What is happening is, the vars set on the first widget call (they are same name as second widget call), get cached, meaning values from the first call are passed to same call. It is weird because are different views.
I have tried:
Using clear_vars(): $this->CI->load->clear_vars(), before and after doing load->view on the library.
Calling load->view with empty array, null, etc
Tried to add a prefix with the widget slug to the vars (that works, but I have to send in some way the prefix to the view, so it is not possible due cache issue)
Any ideas?
Here is what should work.
(I took the liberty of simplifying your database call making it require much less processing.)
public function show($widget_id)
{
$data = array();
$widget_id = (int) $widget_id;
$item = $this->CI->db
->get_where('widget', array('id' => $widget_id))
->row_array();
$data['widget_title'] = $item['title'];
$data['widget_content'] = $item['content'];
$widget = $this->CI->load->view('widget/'.$item['source'], $data, TRUE);
//clear the cached variables so the next call to 'show()' is clean
$this->CI->load->clear_vars();
return $widget;
}
On further consideration The call $this->CI->load->clear_vars(); is probably pointless because each time WidgetManager::show() is called the $data var is recreated with exactly the same keys. When the $data var is passed to load->view the new values of $data['widget_title'] and $data['widget_content'] will replace the values in the cached vars using those keys.

Laravel How to get Route Profile based on Route Name

I have this route:
Route::get('/test',['as'=>'test','custom_key'=>'custom_value','uses'=>'TestController#index'])
I've been tried to use $routeProfile=route('test');
But the result is returned url string http://domain.app/test
I need ['as'=>'test','custom_key'=>'custom_value'] so that I can get the $routeProfile['custom_key']
How can I get 'custom_value' based on route name ?
For fastest way, now I use this for my question:
function routeProfile($routeName)
{
$routes = Route::getRoutes();
foreach ($routes as $route) {
$action = $route->getAction();
if (!empty($action['as']) && $routeName == $action['as']) {
$action['methods'] = $route->methods();
$action['parameters'] = $route->parameters();
$action['parametersNames'] = $route->parametersNames();
return $action;
}
}
}
If there's any better answer, I will be appreciate it.
Thanks...
Try this:
use Illuminate\Support\Facades\Route;
$customKey = Route::current()->getAction()['custom_key'];
I believe you are looking for a way to pass variable to your route
Route::get('/test/{custom_key}',[
'uses'=>'TestController#index',
'as'=>'test'
]);
You could generate a valid URL like so using
route('test',['custom_key'=>'custom_key_vale'])
In your view:
<a href="{route('test',['custom_key'=>'custom_key_vale'])}"
In your controller method:
....
public function test(Request $request)
{
$custom_key = $request->custom_key;
}
....
You can try one of the below code:
1. Add use Illuminate\Http\Request; after namespace line code
public function welcome(Request $request)
{
$request->route()->getAction()['custom_key'];
}
2. OR with a facade
Add use Route; after namespace line code
and use below into your method
public function welcome()
{
Route::getCurrentRoute()->getAction()['custom_key'];
}
Both are tested and working fine!

RedBean ORM and Codeigniter, how to make Fuse recognize models loaded from CI default models path?

Codeigniter has its own Models path, where models extend from CI_Model. I'm using RedBean has a library in Codeigniter, loading it on a controller. After loading Rb, I try to use CI Loader to load a model that extends redbean_simplemodel (wish works, there's no error), but the events / methods inside the model have no effect when they're called on bean.
For example,
APPPATH/application/libraries/rb.php
class Rb {
function __construct()
{
// Include database configuration
include(APPPATH.'/config/database.php');
// Get Redbean
include(APPPATH.'/third_party/rb/rb.php');
// Database data
$host = $db[$active_group]['hostname'];
$user = $db[$active_group]['username'];
$pass = $db[$active_group]['password'];
$db = $db[$active_group]['database'];
// Setup DB connection
R::setup("mysql:host=$host;dbname=$db", $user, $pass);
} //end __contruct()
} //end Rb
And then on
APPPATH/application/models/model_song.php
class Model_song extends RedBean_SimpleModel {
public function store() {
if ( $this->title != 'test' ) {
throw new Exception("Illegal title, not equal «test»!");
}
}
}
while on
APPPATH/application/controllers/welcome.php
class Welcome extends CI_Controller {
public function index()
{
$this->load->library('rb');
$this->load->model('model_song');
$song = R::dispense('song');
$song->title = 'bluuuh';
$song->track = 4;
$id = R::store($song);
echo $id;
}
}
My question is, how to make RedBean (FUSE http://redbeanphp.com/#/Fuse) work on Codeigniter ?
Thanks for looking!
----- FOUND SOLUTION!
Actually, it's working! I was trying to place code under my model, method store(). That wont work! I tryed to place a new method called update() and it does work! Check the example below:
class Model_song extends RedBean_SimpleModel {
public function update() {
if ( $this->title != 'test' ) {
throw new Exception("Illegal title!");
}
}
}
The solution is the following:
"Assuming that you've already installed RedBean on Codeigniter"
1) Load the library for «redbean»
2) Using ci_loader, load the desired model (the model must extend redbean_simplemodel)
Thanks for looking! I hope this helps other people too.
The solution is the following:
"Assuming that you've already installed RedBean on Codeigniter"
Load the library for «redbean»
Using ci_loader, load the desired model (the model must extend redbean_simplemodel)

declaring class level variables in codeigniter

I am new to CI and what I want to do is to have a class level variable (which e.g is an array). But it seems like CI, despite all high bragging, doesn't support this feature. Nothing has been mentioned in the user guide about it. There is a heading called private functions and variables but the text has been seemingly kept silent regarding variables.
I want to have something like :
class OrderStats extends CI_Controller {
protected $arr_CoreCountry = ('0'=>'uk', '1'=>'us');
public function __construct()
{
parent::__construct();
// Your own constructor code
}
public function index()
{
$this->load->model('orders', '', TRUE);
//$data['result'] = $this->Testmodel->get_entries();
$data['result'] = $this->Testmodel->get_reports();
$this->load->view('test', $data);
}
public function getOrderStats()
{
$this->load->model('Orderstatsmodel', '', TRUE);
//$data['result'] = $this->Testmodel->get_entries();
foreach ($arr_CoreCountry as $key => $value)
{
$data['result'] = $this->Orderstatsmodel->get_orderStats($key);
}
// $data['result'] = $this->Orderstatsmodel->get_orderStats(0);
$this->load->view('orderstats', $data);
}
Remember, when I declare $arr_CoreCountry variable at the place as it is in this post, I constantly see a syntax error message.
When I place it some where inside any function then of course, it gets out of scope and I keep getting an error messag that $arr_CoreCountry is an undefined variable.
So the question is where do I define it?
Expect a quick response as half of my day has been wasted just because of this s*** from codeigniter.
This should work:
class OrderStats extends CI_Controller {
protected $arr_CoreCountry = array('0'=>'uk', '1'=>'us');
public function getOrderStats()
{
$this->load->model('Orderstatsmodel', '', TRUE);
//$data['result'] = $this->Testmodel->get_entries();
foreach ($this->arr_CoreCountry as $key => $value)
// etc
}
you are omitting the $this-> in your original code.
Edit
Here was my test code ~
class Testing extends CI_Controller {
protected $foo = array('test'=>'foo', 'bar'=>'baz');
function index() {
foreach($this->foo as $k => $v) {
echo $k . ' = ' . $v . '<br />';
}
}
}
// outputs:
test = foo
bar = baz
perhaps you can post your syntax errors as they appear to be missing from your original post.
You have a syntax array declaration error. Please try to declare array like this:
protected $arr_CoreCountry = array('0'=>'uk', '1'=>'us');
Please check out this site for array manual: http://php.net/manual/en/language.types.array.php
I solved the problem myself.
There are two things which I changed
protected $arr_CoreCountry = ('0'=>'uk', '1'=>'us');
was changed to
var $arr_CoreCountry = array(0=>'se', 1=>'fi',2=>'de');
and
foreach ($arr_CoreCountry as $key => $value)
was changed to
foreach ($this->arr_CoreCountry as $key => $value)
I was missing $this but when I put it there, it was still not working. When I changed protected to var, it worked.
Thanks everyone for your input...

Resources