In Slim Framework, what is a container and what is it for? - slim

I am new to Slim Framework.
There is this dependency container.
What is that?
How is it used?
And can we avoid or not use that?

Slim uses a dependency container to prepare, manage, and inject application dependencies. Unlike its previous version, Slim 4 no longer ships with or depends on a dependency container to work and is now totally optional. If you decide your application requires one, you need to bring it in yourself provide an instance of it to AppFactory before creating your App.
I personally use League Container
$container = new League\Container\Container;
Slim\Factory\AppFactory::setContainer($container);
$app = Slim\Factory\AppFactory::create();
You add dependencies to your container like so;
$container->set('myService', function () {
$myService = new MyService();
return $myService;
});
which then allows you to fetch dependencies from your container from inside a Slim application route like this:
$app->get('/foo', function (Request $request, Response $response, $args) {
$myService = $this->get('myService');
// ...do something with $myService...
return $response;
});
You can read the current docs for v4 here

Related

Pass an variable to the template from the middleware in TYPO3 11.5

I want to parse my .browserslistrc in the middleware of TYPO3 to decide which build should be loaded. Yes, I know that I can do it in JavaScript but I want to make the decision earlier.
This is what I return in the process() function:
$response = $handler->handle($request->withAttribute('isModernBrowser', $isModern));
return $response;
isModern is just a boolean which contains the information if a modern or an "old" browser calls the page.
How can I catch isModern in my template?
ServerRequest is available in $GLOBALS['TYPO3_REQUEST']. Add this object or the specific attribute with $GLOBALS['TYPO3_REQUEST']->getAttribute('isModernBrowser') to view.

how to call using the rest_client in codeigniter

I am new to CodeIgniter and Rest API. I am trying to implement REST API in CodeIgniter and have used Phil Sturgeon's rest-client and rest-server. I have watched few tutorials and have successfully implemented the Rest-Server part (checking with Chrome's Rest Client APP). But, to implement the Rest-Client, I am having few troubles.
Do I need to have cURL and CodeIgniter's cUrl Library?
If yes, how should I set it up?
I watched this tutorial too by Phil Sturgeon but in this tutorial, he has only used the Rest-Client function to call the Server. But not defined where to put it. Here's the code
function rest_client($id){
$this->load->library('rest', array(
'server' => 'http://localhost/rest/index.php/restgetcontroller/',
));
$user = $this->rest->get('user', array('id' => $id), 'json');
echo $user->name;
}
I am sorry if it is too simple.
Thank You
Edit: I made a Client controller and put there a method to call it. But when I load the page, I get this error.
Call to undefined method CI_Loader::spark()
You can use wherever you need to retrieve a value from your API.
$user will have a value you can use for your purpose.
Basically, you would use the API where you used to use a Model, because now the interaction with the database is made with the API, not from your Controllers directly.
To call RESTful APIs you'll require CURL, there's a library called Guzzlehttp to use CURL more efficiently.
You can use composer to install the library or simply download the zip and require it in your controller.
Example Usage:
try {
$guzzleHttp = new GuzzleHttp\Client([
'verify' => false
]);
$http_response = $guzzleHttp->request('GET', 'http://localhost/rest/index.php/restgetcontroller/');
$response = json_decode($http_response->getBody()->getContents());
return $data;
} catch (Exception $e) {
log_message('error', $e->getMessage());
return false;
}

Karma/Jasmine Unit Testing an AngularJS Service with Dependencies

I'm a novice programmer who is very new to both AngularJS and the practice of unit testing. I've spent hours trying to find the solution to this but I'm becoming increasingly more confused. If anyone could point me in the right direction I would greatly appreciate it. I'll try to be as descriptive as possible.
The situation is this:
I have created a service in AngularJS (Service A) that has a couple of functions. Each of these functions makes an $http GET request to a REST API and returns an $http promise object that contains JSON data. Within these functions, the URL is constructed through the implementation of another very simple service (Service B) that has been injected as a dependency into Service A. I have created a mock of Service B to isolate it from all of its dependencies. Both of these services are defined inside of the same module named "services". In this case, there is no real need for this dependency but I just want to understand how it works.
Using Jasmine, I would like to construct a unit test for Service A to ensure that the requests it is making to the API are constructed correctly and possibly if the correct JSON data is being returned. At the same time, I do not want any real API calls to be made.
This is what I know:
$httpBackend mock is what I need to be able to make fake calls to the API and it provides functionality to expect certain requests and return specified results.
I need to test the real Service A and inject the mock I've created of Service B. I know there are ways to do this using Jasmine Spies and $provide. I've also seen examples where sinon.js is used, and I'm not sure which is the best approach.
I will post my source code below, which is written in CoffeeScript.
Service A:
'use strict'
angular.module("services")
.service("ServiceA", ["$http", "ServiceB", ($http, ServiceB) ->
#Uses underscore.js to set this default attribute
defaults = withCredentials:true
getVarset: (itemName, options={}) ->
options.method = "GET"
options.url = ServiceB.makeUrl("item/#{itemName}")
$http _.defaults(options, defaults)
getVarsets: (options = {}) ->
options.method = "GET"
options.url = ServiceB.makeUrl("items")
$http _.defaults(options, defaults)
getModelsForVarset: (itemName, options = {}) ->
options.method = "GET"
options.url = ServiceB.makeUrl("item/#{itemName}/prices")
$http _.defaults(options, defaults)
])
Service B:
'use strict'
angular.module('services')
.service 'ServiceB', [ ->
# Just return the string
# This service builds the real URL, but I've removed this
makeUrl: (Url) ->
"#{Url}"
]
so are you saying that you know how to do this with $provide/Jasmine spies and are looking for alternatives? I've mostly just used the $provide/spy method for mocking and it's worked out really well for me so far.
something like:
beforeEach(function() {
// set up a default value for your mock
bMock = {
makeUrl: jasmine.createSpy('makeUrl() mock').andReturn('http://www....')
}
// use the $provide service to replace ServiceB
// with your mock
module('services', function($provide) {
$provide.value('ServiceB', bMock);
});
});
it('should do what its supposed to do', function() {
// test...
});
then, if you want to use $httpBackend to mock the http requests in service A, you just need to use the $injector service to grab $httpBackend, then call .when(...) on it to set things up, a la http://docs.angularjs.org/api/ngMock.$httpBackend

Zend Framework website.com/username

One of the application I am developing using Zend Framework requires the user's profile page to be accessed via website.com/username, while other pages should be accessed by website.com/controller_name/action_name
I am not too sure how can this be achieved, however, I feel this can be done with some tweaks in the .htaccess file.
Can someone here please help me out?
Many thanks in advance
As suggested before, you can use a custom route that will route single level requests. However, this will also override the default route. If you're using modules, this will no longer work example.com/<module>.
I have done this before but only for static pages. I wanted this:
example.com/about
instead of this:
example.com/<some-id>/about
while maintaining the default route so this still works
example.com/<module>
example.com/<controller>
The way I did this was using a plugin to test if my request could be dispatched. If the request could not be dispatched using the default route, then I would change the request to the proper module to load my page. Here is a sample plugin:
class My_Controller_Plugin_UsernameRoute extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$dispatcher = Zend_Controller_Front::getInstance()->getDispatcher();
if (!$dispatcher->isDispatchable($request)) {
$username = $request->getControllerName();
$request->setModuleName('users');
$request->setControllerName('dashboard');
$request->setActionName('index');
$request->setParam('username', $username);
/** Prevents infinite loop if you make a mistake in the new request **/
if ($dispatcher->isDispatchable($request)) {
$request->setDispatched(false);
}
}
}
}
What about using Zend_Controller_Router_Route, look here the link http://framework.zend.com/manual/en/zend.controller.router.html#zend.controller.router.routes.standard.variable-requirements

Zend Framework: How to disable default routing?

I've spent many hours trying to get this to work. And I'm getting quite desperate.
Would be great if someone out there could help me out :)
Currently using Zend Framework 1.9.5, though I have been struggling to get this to work for many versions now.
What I want to do is provide my own routes through an XML config, and make sure that everything that is not defined in my config will end up on my errorController.
(preferably in a way so I can em apart from EXCEPTION_NO_CONTROLLER and EXCEPTION_NO_ACTION)
I figured that this means I have to get rid of default /:module/:controller/:action and /:controller/:action routes.
So when I tell the router to removeDefaultRoutes(), it won't match these default routes anymore. But now the router is now routing every unrouted route to the defaultcontroller::defaultaction (What the ??)
$front->getRouter()->removeDefaultRoutes();
So, anyone know how to make the frontcontroller (or a part of it) throw an exception when an URI can not be routed?
Reason I want to do this is to prevent duplicate content, and have better 404 pages (in this case, no controller / no action errors are actually application errors instead of not-found)
did you try adding a new route like
$route = new Zend_Controller_Router_Route('*', array('controller'=>'error', 'module'=>'default', 'action'=>'error'));
$router->addRoute('default', $route);
You need to add this route first as it needs to be the last processed.
Fast forward in time to one year later... (time travel music)
Here's another way that I think is much less "intrusive". You can write a plugin to catch the default route and when that happens just throw an exception which at the end of the whole cycle gets translated into a 404 by the front controller.
class Application_Plugin_DisableDefaultRoutes extends Zend_Controller_Plugin_Abstract
{
public function routeShutdown(Zend_Controller_Request_Abstract $request)
{
$front = Zend_Controller_Front::getInstance();
$currentRoute = $front->getRouter()->getCurrentRouteName();
if ($currentRoute == 'default') {
throw new Exception('Default route is disabled');
}
}
}
You can load your plugin in Bootstrap.php
protected function _initPlugins()
{
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Application_Plugin_DisableDefaultRoutes());
}
With this way you can load the plugin in the production machine and leave it out in development where you might want to use the default route for quick tests or something else.