how can I use custom extenstion/widget in yii2? - php

I use gii to generate a extension in yii2.0, here is the code
namespace ms\editor;
/**
* This is just an example.
*/
class AutoloadExample extends \yii\base\Widget
{
public function run()
{
return "Hello!";
}
}
when I want to use it in my view file,
use ms\editor\AutoloadExample;
...
<?= AutoloadExample::widget();?>
I use yii2 baisic template, and I put the "ms" folder in "vendor" folder, but it just tell me class ms\editor\AutoloadExample not found, what should I to make yii2 to find the class?is there something like "components"or "extension" folder in yii1.1?
can you help me?

Your widget should inherit the CWidget class and place the widget in components.
public class AutoloadExample extends CWidget
{
public function run() { }
}
You can then run the widget in your view like this;
$this->widget('application.components.AutoloadExample', array('your variables'));

Would you try one such?
for example create a file in "app/frontend/widgets/"
File Name : Deneme.php
<?php
namespace frontend\widgets;
class Deneme
{
static function yazdir () {
echo 'asd';
}
}
To use;
use frontend\widgets\Deneme;
Deneme::yazdir();

Related

CodeIgniter 4: Autoload Library

I'm using the latest 'master' branch of CodeIgniter 4
I have a Library that I'm trying to load automatically. Effectively, I want to have have 'one' index.php (that has meta, the basic html structure, etc) through which I can load views via my 'Template' Library.
My Library file: (~/app/Libraries/Template.php)
//class Template extends CI_Controller
class Template {
/* This throws an error, but I will open up a separte thread for this
public function __construct() {
parent::__construct();
}
*/
public function render($view, $data = array()) {
$data['content_view'] = $view;
return view('layout/index', $data);
}
}
I also have a controller set up:
class Locations extends BaseController
{
public function index()
{
return $this->template->render("locations/index", $view_data);
//return view('locations/index');
}
//--------------------------------------------------------------------
}
In ~/app/Config/ I added my Library
$classmap = [
'Template' => APPPATH .'/Libraries/Template.php'
];
I'm getting the following error:
Call to a member function render() on null
What am I doing wrong that's causing my library not to load?
In CI4 the BaseController is where you create things that you want to be used by multiple other controllers. Creating classes that extend others is so very easy in CI4.
It seems to me that the only thing you are missing is creating the Template class. (There are a couple of other minor things too, but who am I to point fingers?)
One big item that might be just that you don't show it even though you are doing it. That is using namespace and use directives. They are must-do items for CI 4.
Because of where you have put your files you don't need and should remove the following. See how I've used use which imports namespace already known to the autoloader.
$classmap = [
'Template' => APPPATH .'/Libraries/Template.php'
];
First, the BaseController
/app/Controllers/BaseController.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Libraries\Template;
class BaseController extends Controller
{
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* #var array
*/
protected $helpers = [];
protected $template;
/**
* Constructor.
*/
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
$this->template = new Template();
}
}
/app/Controllers/Locations.php
class Locations extends BaseController
{
public function index()
{
// set $viewData somehow
$viewData['someVar'] = "By Magic!";
return $this->template->render("locations/index", $viewData);
}
}
/app/Libraries/Template.php
<?php namespace App\Libraries;
class Template
{
public function render($view, $data = [])
{
return view($view, $data);
}
}
/app/Views/locations/index.php
This works as if... <strong><?= $someVar; ?></strong>
I know I haven't created exactly what you want to do. But the above should get you where you want to go. I hope so anyway.
It's tricky at first.
But I managed to run it successfully
Make sure you give it proper namespace
And then just "use" in your controller Location.
I dont change anything on Autoload.php.
app/Libraries/Template.php
<?php
namespace App\Libraries;
class Template {
public static function render($param) {
return 'Hello '.ucwords($param);
}
}
The proper way to call is put use App\Libraries\Template just before class Location extends BaseController
app/Controllers/Locations.php
<?php
namespace App\Controllers;
use App\Libraries\Template;
class Locations extends BaseController {
public function index() {
$template = new Template();
$renderedStuff = $template->render('World!');
echo $renderedStuff;
}
}
How does this work?
Notice in Template.php there is a namespace namespace App\Libraries;, so CI4 will automatically load that library properly also recognize the "Template" class. That is proper way to create CI4 libraries in my point of view.
How do we use that library?
Look at my example of Locations.php and then see this code use App\Libraries\Template;, that's how we call that libraries.
How do we call the function?
Look inside the index() function, here we call class Template using var $template = new Template();.
Then we call render() function in Template library with $template->render('World!');.
Just as simple as that.
I hope thats help, lemme know if it doesnt works. :)
Just a little hint, as my eye was hooked by the CI_Controller part.
You seems to use CI3 syntax within CI4, at least about loading the view, which translates to just:
$data = [
'title' => 'Some title',
];
echo view('news_template', $data);
See the CI3doc vs the CI4doc , the "static page" tutorial.

Laravel, is there a way to include codes from resource/view path into controller?

My goal is to include codes from another sources which is located in resources/views. I have tried using resource_path('views/myfiles.php') but it does nothing.
Controller
class MyController extends Controller
{
public function test(Request $request)
{
if($request->input('name') == "chair")
{
$theFilesLocation = "resources.views" . $request->input('name');
#include($theFilesLocation) //something like this
}
}
}
myfiles.php
<?php
dump("if this shows up, then the code works")
?>
Try bellow code but I think it is not a good way.
class MyController extends Controller
{
require_one(resource_path('views/myfile');
}
Or with Laravel File facade
class MyController extends Controller
{
\File::requireOnce(resource_path('views/myfile');
}
You should create a class and put your code there then call it from the controller is a better solution.
What you are looking for is a trait. This allows the easy sharing of code and functionality without having to inherit from a specific base class causing an inheritance hell.
namespace MyCode\Traits;
trait SharedCodeForThing {
public function blaTheBla() {
dump("if this shows up, then the code works");
}
}
and then in your controller
use MyCode\Traits\SharedCodeForThing ;
class MyController extends Controller
{
use SharedCodeForThing;
}
Now if you wish to just render the contents of the view which it seems you're after:
public function test(Request $request)
{
if($request->input('name') == "chair")
{
$view = view('resources.views' . $request->input('name'));
return $view->render();//or echo $view->render(); whatever you like
}
}

create a custom external class in laravel 5.5

I would like to create an external class in Laravel, I want to use this class in my cotroller function.
What is the best way to do that?
thanks
Create a class and define its namespace. For example:
<?php
namespace App\Services;
class MyClass
{
public function doSomething()
{
dd('It\'s working');
}
}
Run composer du command.
You'll be able to use the class in a controller with:
(new App\Services\MyClass)->doSomething();
Or with IoC:
app('App\Services\MyClass')->doSomething();
If you're using IoC, you'll also be able to inject the class into controller constructor:
use App\Services\MyClass;
protected $myClass;
public function __construct(MyClass $myclass)
{
$this->myClass = $myClass;
}
public function index()
{
$this->myClass->doSomething();
}
Used common function any file like controller,models and all blade file valid.
Please try your helpers.php file inner created.
file path like : laravel/app/helpers.php
Code
if (!function_exists('classActivePath')) {
function classActivePath($path) {
return Request::is($path) ? ' class="active"' : '';
}
}

Symfony2: How to call PHP function from controller?

I need use a PHP function to convert numbers to letters. I create a file named: converter.php in the folder “Controller”. I need call the function named “convertir_numero_letras($number)” insert in converter.php.
I call the function “convertir_numero_letras($number)” from the following controller:
public function convertirAction()
{
$number=1234;
$this->convertir_numero_letras($number);
return $this->render('contratos/mostrar_cifra.html.twig', array('numero_convertido' => $numero_convertido));
}
But this code not work. I obtain the following
error message:
Attempted to call an undefined method named "convertir_numero_letras" of class "BackendBundle\Controller\ContratosController".
As I can fix this?
you can create a folder inside bundle like yourBundel/Helper
and create you custom class in folder like ConverHelper.php
like this :
class ConvertHelper
{
public static function numero_letras($param)
{
return 'converted value';
}
}
and then you can call in any controller and any bundle like this:
yourBundle\helper\ConverterHelper::numero_letras('someting');
don't forget to add namespace of ConverterHelper to your contoller file
example:
// file: GRF/BlogBundle/Helper/ConverterHelper.php
<?php
namespace GRF\BlogBundle\Helper;
class ConverterHelper
{
public static function toNum($param)
{
return $param;
}
}
and usage in controller:
//file controller
<?php
namespace GRF\BlogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class PostController extends Controller
{
public function indexAction()
{
return new Response(\GRF\BlogBundle\Helper\ConverterHelper::toNum(32434));
}
}

Yii 2 - using custom helpers

I'm trying to use a custom helper class which i create under frontend/components/Helper (Helper.php)
The content of that file is something like:
<?php
namespace frontend\components\Helper;
class Helper {
public static function helperGreetings() {
echo("hello helper");
}
}
?>
and on my SiteController.php i have the following:
use frontend\components\Helper;
class SiteController extends Controller
{
public function actionIndex()
{
Helper::helperGreetings();
return $this->render('index');
}
}
What should i do to have it working?
BTW, the error i get is Unknown Class – yii\base\UnknownClassException
Unable to find 'frontend\components\Helper' in file: /Users/foo/sites/bar.dev/frontend/components/Helper.php. Namespace missing?
Change the namespace in the Helper class from
namespace frontend\components\Helper;
to
namespace frontend\components;

Categories