Laravel 4: Passing data from make to the service provider - laravel

The code below says it all...
// routes.php
App::make('SimpleGeo',array('test')); <- passing array('test')
// SimpleGeoServiceProvider.php
public function register()
{
$this->app['SimpleGeo'] = $this->app->share(function($app)
{
return new SimpleGeo($what_goes_here);
});
}
// SimpleGeo.php
class SimpleGeo
{
protected $_test;
public function __construct($test) <- need array('test')
{
$this->_test = $test;
}
public function getTest()
{
return $this->_test;
}
}

You can try to bind the class with the parameters directly into your app container, like
<?php // This is your SimpleGeoServiceProvider.php
use Illuminate\Support\ServiceProvider;
Class SimpleGeoServiceProvider extends ServiceProvider {
public function register()
{
$this->app->bind('SimpleGeo', function($app, $parameters)
{
return new SimpleGeo($parameters);
});
}
}
leaving untouched your SimpleGeo.php. You can test it in your routes.php
$test = App::make('SimpleGeo', array('test'));
var_dump ($test);

You need to pass your test array to the class inside of the service provider
// NOT in routes.php but when u need it like the controller
App::make('SimpleGeo'); // <- and don't pass array('test')
public function register()
{
$this->app['SimpleGeo'] = $this->app->share(function($app)
{
return new SimpleGeo(array('test'));
});
}
YourController.php
Public Class YourController
{
public function __construct()
{
$this->simpleGeo = App::make('SimpleGeo');
}
}

Related

Problem for working with DTO - Laravel, PHP

For example I have code like this:
$this->users = $data['data'];
$this->month = $data['month'];
$this->year = $data['year'];
But I need to use DTO. For example I used this function in DTO class:
public function getUsers(): string
{
return $this->users;
}
And as I understand I need to add it to the first code. But I don't understand how to use DTO for my the first code. Can you explain me please?
upd
Now I have:
public function __construct($data, $jobWatcherId)
{
$this->jobWatcherId = $jobWatcherId;
$jobsDTO = new JobsDTO($data['data'], $data['month'], $data['year'],
$data['working_days'], $data['holiday_hours'],
$data['advance_payroll_date'], $data['main_payroll_date']);
}
public function handle()
{
$jobWatcher = JobWatcher::find($this->jobWatcherId);
try {
$startedAt = now();
$jobWatcher->update([
'status_id' => JobWatcherStatusEnum::PROCESSING,
'started_at' => $startedAt,
]);
$redmineService = new RedmineAPIService();
foreach ($jobsDTO->getUsers() as $user) {
}
And for line foreach ($jobsDTO->getUsers() as $user) I have Undefined variable '$jobsDTO'
Your question is a bit unclear, but as I understand it, you want to instantiate a DTO with the above data?
You could have a class like:
class UsersDTO
{
public array $users;
public int $month;
public int $year;
public function __construct(array $users, int $month, int $year)
{
$this->users = $users;
$this->month = $month;
$this->year = $year;
}
public function getUsers(): array
{
return $this->users;
}
public function getMonth(): int
{
return $this->month;
}
public function getYear(): int
{
return $this->year;
}
}
and then somewhere else call:
$usersDTO = new UsersDTO($data['data'], $data['month'], $data['year']);
// Do something with $usersDTO->getUsers();

Can't do pagination in laravel

I need to do a pagination of the data I retrieve from the DB but I get this error:
Call to undefined method App\Models\DataFromRasp::table()
I followed the Laravel documentation but I still getting this error
My controller is this:
class DeviceController extends Controller
{
public function index()
{
$data=Device::all();
return view('backend.auth.user.device', compact("data"));
}
public function create()
{
}
public function store(Request $request)
{
}
public function show(Device $deviceID)
{
$device = Device::firstWhere('id', $deviceID);
return view('backend.auth.user.singleDevice', compact("device"));
}
public function edit(Device $device)
{
//
}
public function update(Request $request, Device $device)
{
//
}
public function destroy(Device $device)
{
//
}
public function visualizeData()
{
$data=DataFromRasp::table('data_from_rasp')->simplePaginate(10);
return view('backend.auth.user.dictionary', compact("data"));
}
public function getData(Request $request)
{
$m_data = $request->get('m_data');
$r_data = $request->get('r_data');
DataFromRasp::create(['MAC' => $m_data, 'RSSI' => $r_data]);
if(($m_data == 'C4:A5:DF:24:05:7E' or $m_data == '70:1C:E7:E4:71:DA') and Device::where('MAC_ADDR', $request->m_data)->doesntExist()){
Device::create(['MAC_ADDR' => $m_data]);
}
}
public function scan()
{
$process = new Process(['python2','C:\Simone\Università\Smart IoT Devices\Lab_Raspy\Bluetooth\prova.py']);
$process->run();
if (!$process->isSuccessful()) { throw new ProcessFailedException($process); }
return redirect()->route('dict');
}
}
The route is:
Route::get('dict', [DeviceController::class, 'visualizeData'])->name('dict');
Can someone help me?
try $data = DataFromRasp::paginate(10)

How to mock a response from a package?

I am trying to mock a response while using php-oppwa
I created this wrapper around that package:
use Bryangruneberg\OPPWA\Factory;
use Bryangruneberg\OPPWA\OPPWAResponse;
use Illuminate\Support\Facades\Config;
class OppwaService
{
public function client()
{
$client = Factory::createClient(
Config::get('gateways.oopwa_user_id'),
Config::get('gateways.oopwa_password'),
Config::get('gateways.oopwa_entity_id'),
Config::get('gateways.oopwa_url'),
);
$api = Factory::createAPI($client);
return $api;
}
public function setupCheckout(int $amount, string $currency, string $paymentType, array $options = [])
{
return $this->client()->prepareCheckout($amount, $currency, $paymentType, $options);
}
public function checkoutSetupWasSuccessful(OPPWAResponse $response)
{
return $this->client()->isPrepareCheckoutSuccess($response);
}
}
And I have this in my controller:
public function __construct(OppwaService $service)
{
$this->service = $service;
}
public function show()
{
$checkout = $this->service->setupCheckout(23, 'USD', OPPWA::PAYMENT_TYPE_DEBIT);
if ($this->service->checkoutSetupWasSuccessful($checkout)) {
$checkoutId = $checkout->getId(); // I am trying to mock this response
}
return view('index',['checkoutId' => $checkoutId ?? null);
}
I am trying to mock getId in my test,
/** #test */
public function checkout_id_exists()
{
$this->mock(OPPWAResponse::class, function ($mock) {
$mock->shouldReceive('getId')->once()->andReturn('555555555-555555555');
});
$this->get(route('checkout.show'))->assertSee('555555555-555555555');
}
But, that doesn't work.. Is it because that OPPWAResponse is in the vendor directory?
How can I mock the response?

Create public funtion in controller using for loop laravel

I am trying to create public funtions using for loop
here is an example about what I want to do:
class databaseController extends Controller
{
for ($i=0; $i < 5; $i++) {
# code...
public function create()
{
// dd('hoi_tb1_create');
if (Auth::guard('admin')->user()->level == 2) {
Schema::connection('mysql')->create('tb' . $i, function (
$table
) {
$table->increments('id');
});
}
// get all products
}
}
}
have you any idea how to do that?
Thanks in advance
Somur
You could use a second function to get this to work
class LoopController extends Controller
{
public function create($i)
{
if (Auth::guard('admin')->user()->level == 2) {
Schema::connection('mysql')->create('tb' . $i, function ($table) {
$table->increments('id');
});
}
}
public function createMany()
{
for($i = 0; $i < 5; $i++) {
$this->create($i);
}
}
}
The create function takes in a parameter of $i, but is not called directly from the route, instead you'd call createMany() which has a for loop in it. This will call create 5 times, each time passing its iterater value in e.g. 0, 1, 2, 3, 4.
Alternatively, if you're wanting these functions to be invoked independently, you could use PHP's magic method to dynamically call the create function. For example you could grab all of the numbers after create and then call create(numbers);
class LoopController extends Controller
{
public function create($i)
{
if (Auth::guard('admin')->user()->level == 2) {
Schema::connection('mysql')->create('tb' . $i, function ($table) {
$table->increments('id');
});
}
}
public function __call($method, $parameters)
{
if (preg_match('/create([\d]+)/', $method, $matches)) {
return $this->create($matches[1]);
}
throw new \BadMethodCallException("Method " . get_class($this) . "::$method does not exist");
}
}
So now if you call LoopController->create48(); It will then call ->create(48);

Shows an error when using the Gate facade

When writing privileges and rights of a user shows error: 403
Forbidden
Controller code
class IndexController extends AdminController
{
public function __construct(){
parent::__construct();
if (Gate::denies('VIEW_ADMIN')) {
abort(403);
}
$this->template = env('THEME').'.admin.index';
}
AuthServiceProvider code
public function boot()
{
$this->registerPolicies();
Gate::define('VIEW_ADMIN', function($user){
return $user->canDo('VIEW_ADMIN');
});
//
}
Model User code
The User model is associated with the Roles model, and the Roles model is associated with the Permission model.
public function canDo($permission, $require = FALSE){
if (is_array($permission)) {
dump($permission);
}
else{
foreach ($this->roles as $role) {
foreach ($this->permissions as $permission) {
if (str_is($permission,$permission->name)) {
return true;
}
}
}
}
}
You rewrite input $permission on line foreach ($this->permissions as $permission) { so your if (str_is($permission,$permission->name)) is always FALSE because
str_is(array(), 'VIEW_ADMIN') === FALSE
You should do this
public function canDo($permission, $require = FALSE){
if (is_array($permission)) {
dump($permission);
}
else{
foreach ($this->roles as $role) {
foreach ($this->permissions as $permissionObject) {
if (str_is($permission,$permissionObject->name)) {
return true;
}
}
}
}
}
Also you should add return FALSE because return type is boolean in this case.

Resources