I have a custom block that needs to request data from an external API.
Examples refer to a construct like this:
class CustomerBalance extends \Magento\Framework\View\Element\Template
{
public function __construct(
\Magento\Framework\HTTP\ZendClientFactory $httpClientFactory
)
But that breaks the site and the page fails to load correctly without logging any errors.
I have the same problem trying to use GuzzleHttp when I import that.
I guess there is something I'm missing about Magento 2 importing...
Or is there another way to access the Magento curl object?
Any help would be appreciated.
It appears I was simply importing the wrong class. This works:
protected $_httpAdapter;
public function __construct(
\Magento\Framework\HTTP\Adapter\Curl $httpAdapter
){
$this->_httpAdapter = $httpAdapter;
}
A more complete answer can be found here:
https://magento.stackexchange.com/questions/153993/magento-2-curl-send-header-with-response
Related
I have a dynamic website designed with Codeigniter 3 and I am working on the sitemap part as a newbie.
I found the library sitemap-php from evert/sitemap-php but I can't make it run.
From now this is what I did, I put the Sitemap.php file into my library folder
Controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Deals extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->helper('url', 'form', 'security');
$this->load->library('form_validation');
$this->load->library('session');
$this->load->library('email');
$this->load->model('deal_model');
$this->load->helper(array('cookie','custom','text'));
}
public function Sitemap(){
$this->load->library('Sitemap');
$sitemap = new Sitemap('https://www.mywebsite.com');
$sitemap->setPath('/public_html/Sitemap/'); // I created a folder Sitemap into my public folder
$sitemap->setFilename('sitemap');
$sitemap->addItem('/', '1.0', 'daily', 'Today');
$sitemap->createSitemapIndex('https://www.mywebsite.com/sitemap/', 'Today');
}
Then when I go to https://www.mywebsite.com/sitemap/, I have an Error 404.
Could you guide me to solve my issue.
Thanks
The docs for that library describe that it generates a static XML file. The code you've shown will do that - but your code is in a Library, and you have not run it yet. You need to run it, then it will generate an XML file as you've specified, in /public_html/Sitemap/. From your description you are looking for the XML before doing anything to generate it, and it does not (yet) exist.
From your updated code, you now have the code to generate the static XML available as a Controller method. According to the standard Codeigniter routing conventions, the method you have created is accessible at:
http://your-site/deals/Sitemap
(Maybe you've also set up some routes so it is accessible at other URIs also.)
Visit that URL, once, to generate the static XML file at /public_html/Sitemap/sitemap.xml. Assuming your code works, you should then be able to browse the XML at
http://your-site/Sitemap/sitemap.xml
Side note: AFAIK Codeigniter convention is for capitalised Controller file and class names (Deal.php and Deal), but all lower-case method names (sitemap() instead of Sitemap()). You can see examples of this in the Controller docs I linked above. I am not sure if it matters, just pointing it out.
My User_model have a public method called is_unique_email($email). This method checks if a user has a uniqe mail adress with some status flag checks. This is also the reason why I can't use the standard is_unique validation rule from CodeIgniter.
I'm using a form_validation.php with config array for my validation rule groups. My question is: How can I call the model method for checking the new user's e-mail address? I searched and tried so many things, but nothing work. My preferred call would be with | pipe separator.
Like: trim|required|max_length[70]|valid_email|<~ here comes the model callback ~>
Is there any solution for this callback or is there no way and I have to extend the Form_validation system library?
I'm using CodeIgniter 3.1.7.
Thanks in advance!
UPDATE:
Because I've always done things via extending the form_validation library I forgot about this:
https://codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods
and this (anonymous functions):
https://codeigniter.com/user_guide/libraries/form_validation.html#callable-use-anything-as-a-rule
Might be better for you. When in doubt, always read the docs ;)
Yes you can extend the form_validation library. In application/library make a MY_Form_validation.php and have it extend CI's as such:
class MY_Form_validation extends CI_Form_validation {
then in it you can do something like this:
/**
* Checks to see if bot sum is valid
* e.g. equals the session stored values
*
* #param int $sum
* #return boolean
*/
public function valid_bot_sum($sum) {
$generated = $this->CI->session->bot_first_number + $this->CI->session->bot_second_number;
if ($generated !== intval($sum)) {
$this->set_message('valid_bot_sum', 'Invalid bot sum.');
return false;
} else {
return true;
}
}
and now your function can be accessed via pipe separators as any native form_validation validation function. Just be sure to set the message on false as I've done, otherwise you will get an error. You can access the CI instance like so $this->CI.
In your case you can either migrate the function from the model into this file, or you can call it by loading the model in the function and calling the function and just testing to see if it evaluates to true/false and handling as above.
I'm having trouble setting something up that I'm pretty sure /should/ be easy, so I thought I'd throw it to the crowd. I can't seem to find what I'm looking for elsewhere on the web or on SE.
I am simplifying my project of course, but basically I have a JAX-WS annontated Jersey resource class that looks something like this:
#Path("myresource")
public class MyResource {
#Autowired
MyComplexObjectDAO daoInstance;
#Path("findObject/{id}")
#GET
public MyComplexObject findObject( #PathParam(value="id") String id ) {
return daoInstance.findObject( id );
}
#Path("saveObject")
#PUT
public MyComplexObject saveObject( MyComplexObject objectToSave ) {
MyComplexObject savedObject = daoInstance.saveObject( objectToSave );
return savedObject;
}
}
So you can see I'm autowiring a DAO object using spring, and then I use the DAO methods in the REST handlers.
The 'findObject' call seems to work fine - so far it works exactly as I expect it to.
The 'saveObject' call is not working the way I want and that's what I need some advice on.
You can see that I'm trying to directly take an instance of my complex object as a parameter to the REST method. Additionally I would like to return an instance of the complex object after it's been saved.
I put together some 'client' code for testing this out.
#Test
public void saveTest() {
WebResource wsClient = createWebServiceClient();
MyComplexObject unsavedInstance = createMyComplexObject();
MyComplexObject savedInstance =
wsClient
.path("saveObject")
.accept(MediaType.APPLICATION_XML)
.put(MyComplexObject.class, unsavedInstance);
assertNotNull(savedIntent);
}
Which is returning the following error:
com.sun.jersey.api.client.UniformInterfaceException: PUT http://localhost:8081/rest/myresource/save returned a response status of 400 Bad Request
I don't see why this isn't working and I think I've tried just about everything I can think of. Any help or direction would be very much appreciated.
Thanks so much!
I see that you call the accept() method in your test client (which means that a "Accept:" header is added to the request, indicating the server what type of representation you would like). However, you don't call the type() method to add a "Content-type:" header and inform the server that you are sending XML data. See http://jersey.java.net/nonav/documentation/latest/client-api.html#d4e644 for examples.
Side remark: your URLs are not RESTful - you should avoid verbs in your path:
So, instead of:
/api/findObject/{id}
/api/saveObject
You should use:
/api/objects/{id}
/api/objects
Last note: to create an object on calling /api/objects, you should do a POST and not a PUT to adhere to REST best practices and widely adopted patterns.
switching to the 'concrete class' solution I alluded to in my earlier comment is what fixed things up for me.
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
I'm trying to capture a URL parameter in my bootstrap file but after several attempts I'm not able to do it.
I've tried this but it does not work:
protected function _initGetLang() {
$frontController = Zend_Controller_Front::getInstance();
$lang= $frontController->getParam('lang');
}
Is this the right way to do it?
Thks.
You won't be able to access the request params from the bootstrap because it hasn't yet gone through the dispatch/routing process. I think you'd be better served by using a Controller Plugin, performing actions based on the URL is what they do best. Or if you absolutely have to do it in the bootstrap, getRequestUri() or $_GET is available, or you could write a quick script to parse the url yourself.
Edit:
I've done some silly stuff like this in the past before I figured out how plugins work:
/**
* Grab the module name without a request instance
*
* #return string The module name
*/
public static function getModuleName()
{
$uri = ltrim($_SERVER["REQUEST_URI"], "/");
$module = substr($uri, 0, strpos($uri, "/"));
return $module;
}
This would at least give you a module name that you could switch on in the bootstrap. You should be able to do anything you need with the plugins done correctly though.